Idea中完成JDBC的简单增删查改操作,以下为基本步骤:
目录
一、加载驱动
通过初始化驱动类com.mysql.jdbc.Driver,该类就在 mysql-connector-java-5.0.8-bin.jar中。如果你使用的是oracle数据库那么该驱动类将不同。
Class.forName("com.mysql.jdbc.Driver");
注意:Class.forName需要捕获ClassNotFoundException.
二、创建连接
建立JDBC和数据库之间的Connection连接
这里需要提供:
- 数据库所处于的ip:127.0.0.1 (这里是本机,如果连接其他电脑上的数据库,请改变该ip)
- 数据库的端口号: 3306 (mysql专用端口号)
- 数据库名称: user(根据你自己数据库中的名称填写)
- 编码方式 :UTF-8
- 账号: root
- 密码 :xxx(在创建数据库的时候设置的账号和密码)
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/user?useSSL=true&characterEncoding=utf-8&user=root&password=xxx");
三、写SQL语句
给数据库进行增删查改的基本操作sql语句例子:
1、新增用户:
String sql = "insert into userinfo(username,password) values (?,?)";//增
2、删除用户:
String sql= "delete from userinfo where id= ?";//删
3、查询用户:
String sql= "select * from userinfo";//查
4、更新用户:
String sql= "update userinfo set username=?,password=? where id= ?";//改
四、得到statement对象
以新增用户的sql为例,得到statement对象:
PreparedStatement statement = connection.prepareStatement(sql); //增
statement.setString(1, uname);
statement.setString(2, upassword);
五、执行sql得到结果集
以新增用户为例,得到statement对象:
statement.executeUpdate();
六、处理结果集
以查询用户为例,处理结果集:
rs = statement.executeQuery();
while(rs.next()){
System.out.print(rs.getInt(1)+"\t");
System.out.print (rs.getString(2)+"\t");
System.out.print (rs.getString(3)+"\n");
}
七、关闭资源
需要在末尾关闭资源,包括之前打开的连接Connection、Statement对象和结果集ResultSet等。
public static void toClose(ResultSet rs,PreparedStatement statement,Connection connection){
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}