jdbc-mysql笔记

建立连接步骤:

1)利用反射得到Driver类
2)利用DriverManager得到一个链接
3)创建statement对象
4)执行sql

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

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestJdbc {

public static void main(String[] args) {
// TODO Auto-generated method stub
Connection ct = null;
try {
Class.forName("com.mysql.jdbc.Driver");
ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
PreparedStatement preparedStatement = ct.prepareStatement("select * from user1 where id = ?");
preparedStatement.setInt(1, 3);
ResultSet set = preparedStatement.executeQuery();
while(set.next()){
System.out.println(set.getString("name"));
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(ct != null){
try {
ct.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

}