jdbc连接MySql数据库

jdbc连接MySql数据库

jdbc连接MySql数据库与连接Oracle数据库差不多,只是导入驱动包不同,以及注册驱动和获取的连接不同
注册驱动为: com.mysql.jdbc.Driver
MySql连接为:jdbc:mysql://localhost:3306/test

源码如下:

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
package MySQL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/***
*jdbc连接mysql数据库
*
* @author HDC
*
*/
public class Test {
public static void main(String[] args) {
Connection con = null;
Statement stm = null;
ResultSet rs = null;
try {
// 1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获取连接
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin8023");
// 3.获取数据库操作对象
stm = con.createStatement();
// 4.执行操作
String sql = "select * from student";
rs = stm.executeQuery(sql);// 查询用query 增删改用executeUpdate
// 5.处理结果
while (rs.next()) {
System.out.println(rs.getString("name") + "\t" + rs.getString("sex") + "\t" + rs.getInt("age"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}else if(stm!=null){
stm.close();
}else if(con!=null){
con.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!