java链接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
39
40
41
42
43
44
45
46
47
48
49
50
|
import
java.sql.*;
public
class
Hello{
public
static
void
main(String args[]){
String driver =
"com.mysql.jdbc.Driver"
;
String url =
"jdbc:MySQL://127.0.0.1:3306/dbname"
;
String user =
"root"
;
String password =
"123456"
;
try
{
//检测mysql驱动(com.mysql.jdbc.Driver)是否加载成功
Class.forName(driver);
System.out.println(
"成功加载数据库驱动程序"
);
}
catch
(java.lang.ClassNotFoundException e){
System.out.println(
"加载数据库驱动程序失败"
);
System.out.println(e.getMessage());
return
;
}
try
{
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,user,password);
if
(!conn.isClosed()){
System.out.println(
"已成功链接mysql数据库"
);
}
Statement statement = conn.createStatement();
String sql =
"select * from `ad`"
;
ResultSet rs = statement.executeQuery(sql);
System.out.println(
"执行结果如下:"
);
String name =
null
;
while
(rs.next()){
name = rs.getString(
"title"
);
//name = new String(name.getBytes("ISO-8859-1"),"GBK");
System.out.println(rs.getString(
"url"
) +
"\t"
+ name);
}
rs.close();
conn.close();
}
catch
(ClassNotFoundException e){
System.out.println(
"mysql数据库链接失败"
);
e.printStackTrace();
}
catch
(SQLException e){
e.printStackTrace();
}
catch
(Exception e){
//Exception 必须放在最后,否则前面的异常就捕捉不到了
e.printStackTrace();
}
}
}
|
刚开始的时候老是报错:
mysql驱动(com.mysql.jdbc.Driver)加载失败。
解决办法:
原因是没有将mysql-connector-java-5.0.8-bin.jar导入到你的项目中。
导入方法:
http://www.cnblogs.com/taoweiji/archive/2012/12/11/2812295.html
附:
java连接数据库时加载驱动程序Class.forName(driveName)详解
http://bbs.csdn.net/topics/360175763
本文转自许琴 51CTO博客,原文链接:http://blog.51cto.com/xuqin/1307644,如需转载请自行联系原作者