jdbc操作步骤
- 加载数据库连接驱动
- 建立与数据库的连接
- 根据连接生成与数据库对话的对象
- 与数据库进行对话
- 收尾
代码展示
进行操作前数据库表:
import java.sql.*;
public class jdbctest {
public static void main(String[] args){
//加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.err.println("驱动加载失败!!!");
e.printStackTrace();
}
//建立与数据库连接
Connection conn=null;
try {
conn= DriverManager.getConnection("jdbc:mysql://localhost:33060/mytest","root","Root");
} catch (SQLException e) {
System.err.println("数据库连接建立失败!!!");
e.printStackTrace();
}
//根据连接生成与数据库对话的对象
Statement stmt=null;
try {
stmt=conn.createStatement();
} catch (SQLException e) {
System.err.println("生成与数据库对话的对象失败!!!");
e.printStackTrace();
}
//与数据库进行对话
try {
int count=stmt.executeUpdate("insert into s values ('3','ddd','c3',21)");
System.out.println("数据库更新了"+count+"条信息");
} catch (SQLException e) {
System.err.println("对话失败!!!");
e.printStackTrace();
}
//收尾
if (stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
操作后数据库表:
另外,大家对代码有一些疑问,可以参考JDBC、Statement、execute、executeQuery、executeUpdate,或者给我留言。