Java如何把String[]类型的记录插入到Mysql中 您所在的位置:网站首页 mysql字符型怎么写 Java如何把String[]类型的记录插入到Mysql中

Java如何把String[]类型的记录插入到Mysql中

2023-09-10 12:22| 来源: 网络整理| 查看: 265

前言

最近的 Java Web 项目使用了 Mysql 数据库,本文大致讲解了 Java 如何 通过 Jdbc 连接数据库 。其中主要步骤为:安装 Mysql、下载 JDBC 驱动、建立Connection、利用PreparedStatement对 Mysql 插入数据。

本文还记录了使用Mysql遇到的一些坑,并探讨一下如何把数组插入 Mysql中,方案笔者尝试了2个方法:

Arrays.toString( )把数组格式化为[xxx , xxx , xxx ,] 插入 Mysql中。如果有更好的方法,欢迎各位留言。序列化数组,存入 Mysql 的 Blob 类型中,读取的时候需要反序列化

本文地址 http://blog.csdn.net/never_cxb/article/details/50574077 转载请注明出处

本地安装 Mysql 数据库

Mysql 官方网址 http://dev.mysql.com/downloads/mysql/,下载完安装。

具体可以查看这篇文字 关于本地安装 Mysql 的一些坑,记录了笔者安装遇到了一些坑。

下载MySQL Connector/J

通过 JDBC 连接数据库需要Mysql jdbc 驱动。

MySQL Connector/J是MySQL官方JDBC驱动程序,官方下载地址 https://dev.mysql.com/downloads/connector/j/ 。把下载好的mysql-connector-java-5.1.38.jar 加到 Java 工程的Build Path 中。

Note mysql-connector-java-5.1.38.jar 连接 5.0.xx 版本的 Mysql 可能会报下面的错误。这是MySQL Connector/J的一个 Bug,解决方法:换 jar 包,笔者把 jar 包换成了 mysql-connector-java-5.0.8-bin.jar。

java.sql.SQLException: Unknown system variable 'language' at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998) 建表

在数据库中建表可以通过图形化工具,如 MySQLWorkBench、Navicat等等。下图是MySQLWorkBench工具建表的截图。

android

当然也可以通过 Sql 语句来建表了,下面是笔者建表的示例:

CREATE TABLE IF NOT EXISTS `latest` ( `id` int(11) NOT NULL, `image_urls` text, `title` varchar(45) NOT NULL, `publish_date` date NOT NULL, `read_times` int(11) NOT NULL, `source` varchar(10) NOT NULL, `body` text NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id_UNIQUE` (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; Java 代码 建立Mysql Connection

下面的代码he

public class MysqlTool { private static Connection con = null; // 为了方便分析错误,将异常全部抛出到最顶层 public static Connection getConnection() throws Exception { if (con != null) { return con; } // JDBC驱动程序 Class.forName("com.mysql.jdbc.Driver").newInstance(); // 后面unicode和utf8设置防止中文乱码 String url = "jdbc:mysql://127.0.0.1:3306/**database_name**?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=utf-8"; String name = "**user**"; String password = "**password**"; con = DriverManager.getConnection(url, name, password); return con; } public static void closeConnection() { if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }

一般来说 url 只需要 jdbc:mysql://127.0.0.1:3306/**database_name**"就够了,autoReconnect=true是自动重连,useUnicode=true&characterEncoding=utf-8是为了防止插入中文字符乱码。

Mysql 存放数组 public class ArticleItem { private int id; private String[] imageUrls; private String title; private String publishDate; private int readTimes; private String source; private String body; // get set method ignored... }

笔者的需求是把某条新闻记录插入到 Mysql 中,新闻包含了 id、图片、标题、发布时间、阅读次数、信息来源、主题内容。

其中图片可能有多个,笔者使用数组保存图片的 Url。

问题来了?数组类型的对象怎么插入到 Mysql 中。 比如 String [] imageUrls = [1cb92bd38a437236bbf28f75525b644a, ca30033a28dfe266c67c9fea9a108427];,Mysql 中对应的字段取什么类型,怎么插入呢?

笔者是这么处理的,先把 String[] 转化为字符串插入Mysql,再从 Mysql 中读取字符串,把字符串转化为 String[] 。

由于String [] imageUrls的长度不规定,最多可能到10+,大于 varchar(255),所以选用 text 类型,`image_urls text`。

//数组 -> String preparedStmt.setString(2, Arrays.toString(article.getImageUrls())); //逆向,String -> 数组 String[] imageUrls = rs.getString(2).replace("[", "").replace("]", "").split(", "); PHP 序列化数组 存入 Mysql

其他方案可以把数组序列化,存入Mysql Blob 类型的字段,读取的时候 Mysql 中取出记录反序列化为数组。

笔者本来想尝试用 Java 实现这种方案,但发现String[] 类型转化为 byte[]代码比较冗余,得不偿失。

意外看到 PHP 代码(How to store array in mysql?)对于serialize和unserialize支持很好,看来Mysql 和 PHP 更配哟。

将数组插入 Mysql 中

从 Mysql 中读取,反序列化为数组

插入记录,查询记录

预编译的SQL语句存储在PreparedStatement对象中,如果SQL 语句执行多次的话,PreparedStatement的执行效率一般要高于Statement。Sql 语句格式如下:

INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....) public class ArticleDao { private Connection connection; public ArticleDao() throws Exception { connection = MysqlTool.getConnection(); } public int insertArticle(ArticleItem article) throws SQLException { // the mysql insert statement String query = " insert into latest (id, image_urls, title, publish_date, read_times,source,body)" + " values (?, ?, ?, ?, ?,?,?)"; // create the mysql insert preparedstatement PreparedStatement preparedStmt = connection.prepareStatement(query); preparedStmt.setInt(1, article.getId()); preparedStmt.setString(2, Arrays.toString(article.getImageUrls())); preparedStmt.setString(3, article.getTitle()); preparedStmt.setDate(4, Date.valueOf(article.getPublishDate())); preparedStmt.setInt(5, article.getReadTimes()); preparedStmt.setString(6, article.getSource()); preparedStmt.setString(7, article.getBody()); return preparedStmt.executeUpdate(); } }

PreparedStatement不再使用+拼接 Sql 语句的方式,而是通过占位符,使用preparedStmt.setInt() setString() setDate() 来把不同类型的数据插入到 Mysql 中。

public ArticleItem getArticleById(int id) throws SQLException { // the mysql select statement String query = "select * from latest where id = ?"; // create the mysql preparedstatement PreparedStatement preparedStmt = connection.prepareStatement(query); preparedStmt.setInt(1, id); ResultSet rs = preparedStmt.executeQuery(); while (rs.next()) { String[] imageUrls = rs.getString(2).replace("[", "").replace("]", "").split(", "); String title = rs.getString(3); String date = rs.getDate(4).toString(); int readTimes = rs.getInt(5); String source = rs.getString(6); String body = rs.getString(7); ArticleItem article = new ArticleItem(id, imageUrls, title, date, readTimes, source, body); return article; } return null; }

查询的时候返回一个ResultSet,是返回记录的集合 ,通过next()方法可以依次处理每条记录。通过getString() getInt()可以得到各列的数据。

注意 getXxx()方法的参数columnIndex是从1开始的,不是从0。

String getString(int columnIndex) throws SQLException Retrieves the value of the designated column in the current row of this ResultSet object as a String in the Java programming language. Parameters: columnIndex - the first column is 1, the second is 2, ...


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有