建立连接步骤:
1)利用反射得到Driver类 2)利用DriverManager得到一个链接 3)创建statement对象 4)执行sql
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();
}
}
}
}
}