java mysql插入string_Java如何把String[]類型的記錄插入到Mysql中

前言

最近的 Java Web 項目使用了 Mysql 數據庫,本文大致講解了 Java 如何 通過 Jdbc 連接數據庫 。其中主要步驟為:安裝 Mysql、下載 JDBC 驅動、建立Connection、利用PreparedStatement對 Mysql 插入數據。

本文還記錄了使用Mysql遇到的一些坑,並探討一下如何把數組插入 Mysql中,方案筆者嘗試了2個方法:

Arrays.toString( )把數組格式化為[xxx , xxx , xxx ,] 插入 Mysql中。如果有更好的方法,歡迎各位留言。

序列化數組,存入 Mysql 的 Blob 類型中,讀取的時候需要反序列化

本地安裝 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工具建表的截圖。

1aab7129a9447639045f787d4fdf6500.png

當然也可以通過 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

下面的代碼hepublic 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 中

$array = array("foo", "bar", "hello", "world");

$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');

mysql_select_db("mysql_db",$conn);

$array_string=mysql_escape_string(serialize($array));

mysql_query("insert into table (column) values($array_string)",$conn);

?>

從 Mysql 中讀取,反序列化為數組

$conn=mysql_connect('localhost', 'mysql_user', 'mysql_password');

mysql_select_db("mysql_db",$conn);

$q=mysql_query("select column from table",$conn);

while($rs=mysql_fetch_assoc($q))

{

$array= unserialize($rs['column']);

print_r($array);

}

?>

插入記錄,查詢記錄

預編譯的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, ...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值