Java Data Base Connectivity
JDBC编程步骤:
1.Load the Driver
Class.forName() | Class.forName().newInstance() | new DriverName()
2.Connect to Database
DriverManager.getConnection()
3.Execute SQL
Connection.createStatement();
Statement.executeQuery(); //查询
Statement.executeUpdate(); //增、删、改
4.Retrieve the result data
循环取得结果 while(ResultSet.next())
5.Show result data
将数据库中的各种类型转换为Java中的类型
6.Close
close ResultSet / close Statement /close Connection
示例:
import java.sql.*;
public class example {
public void getConnection() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/jdbc",
"root","root");
Statement stmt = conn.createStatement();
String sql = "select * from TableName";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
String name = rs.getString(1);
}
rs.close();
stmt.close();
conn.close();
}
}