JDBC链接的步骤:
1. 把jar放入到工程下并add Libaray
2. 加载驱动 Class.forName("com.mysql.cj.jdbc.Driver");
3. 获取链接对象
Connection connection=DriverManager.getConnection(url,user,password);
4. 获取执行sql语句的对象: Statement statement=connection.createStatement();
5. 执行sql语句 int row=statement.executeUpdate(sql); 或 ResultSet resultSet=statement.executeQuery(sql); 遍历结果集
6. 关闭资源
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Jdbc07 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ceshi?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai","root","123456");
String sql = "insert into student values(?,?,?,?)";
ps = conn.prepareStatement(sql);
Object[] objects = {5,"老代",15,3};
for (int i =1;i<=objects.length;i++){
ps.setObject(i,objects[i-1]);
}
int j = ps.executeUpdate();
System.out.println(j);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
if(ps!=null){
ps.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
try {
if(conn!=null) {
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}