以前用JDBC操作mysql是这样的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
/**
* 1.插入数据时jdbc写法:
*/
public
static
void
main(String[] args)
throws
Exception {
//1.加载数据库驱动
Class.forName(
"com.mysql.jdbc.Driver"
);
//括号里是:数据库驱动类的完全限定名
//2.获取数据库的连接
Connection con = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/mydb"
,
"root"
,
"root"
);
/**
* 注意事项:Connection来自于java.sql.Connection;mydb是数据库名称;
* root分别是数据库连接的用户名和密码,3306是mysql的端口号。
*/
//3.获取PreparedStatement对象
String sql =
"insert into t_user(username,address) values('韩','北京')"
;
//String sql = "insert into t_student(name) values('中文')";
PreparedStatement sta = con.prepareStatement(sql);
/**
* 注意事项:PreparedStatement来自于java.sql.PreparedStatemet
*/
//4.执行SQL语句
int
rows = sta.executeUpdate();
if
(rows >
0
) {
System.out.println(
"操作成功!"
);
}
//释放资源
sta.close();
con.close();
/**
* 注意事项:要先关闭sta,再关闭con
*/
}
|
但是,今天不知道为什么就插入数据库的中文数据就变成了??
参考了此片博文:http://blog.youkuaiyun.com/gjife/article/details/7005655
用这种方法再操作就不会出现中文乱码的问题:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
public
static
void
main(String[] args)
throws
Exception {
String hostip =
"127.0.0.1"
;
String DBname =
"mydb"
;
String user =
"root"
;
String passwd =
"root"
;
//1.加载数据库驱动
Class.forName(
"com.mysql.jdbc.Driver"
).newInstance();
//2.获取数据库的连接
Connection con=DriverManager.getConnection(
"jdbc:mysql://"
+hostip +
"/"
+DBname+
"?user="
+user+
"&password="
+passwd+
"&useUnicode=true&characterEncoding=utf-8"
);
//3.获取PreparedStatement对象
String sql =
"insert into t_user(username,address) values('韩','北京')"
;
//String sql = "insert into t_student(name) values('中文')";
PreparedStatement sta = con.prepareStatement(sql);
/**
* 注意事项:PreparedStatement来自于java.sql.PreparedStatemet
*/
//4.执行SQL语句
int
rows = sta.executeUpdate();
if
(rows >
0
) {
System.out.println(
"操作成功!"
);
}
//释放资源
sta.close();
con.close();
/**
* 注意事项:要先关闭sta,再关闭con
*/
}
|
http://ocaicai.iteye.com/blog/1138479
可以参考下这篇关于中文乱码的文章
本文转自韩立伟 51CTO博客,原文链接:http://blog.51cto.com/hanchaohan/925247,如需转载请自行联系原作者