暑期实习②-----JDBC的入门
1.加载驱动
2.创建连接
3.写sql
4.创建一个statement对象
5.执行sql,并得到结果集
6.处理结果集
7.关闭JDBC对象,释放资源
代码如下:
主文件:
package adil;
import java.sql.*;
public class che {
public static void main(String[] args)
{
Connection connection=null;
ResultSet resultSet=null;
PreparedStatement statement=null;
//1.加载驱动
try {
Class.forName(“com.mysql.jdbc.Driver”);
//2.创建连接
connection= DBUtil.getConnection();//此处DBUtil是自己设计的工具类,里面有相关的功
//能函数,例如连接数据库的代码段就在getConnection()中。
System.out.print(“创建连接成功”);
//3.写sql
String sql=“select * from userinfo”;
//4.得到statement对象
statement=connection.prepareStatement(sql);
//5.执行sql 得到结果集
resultSet=statement.executeQuery();
//6.处理结果集
while (resultSet.next()) {
System.out.println(resultSet.getInt(1));
System.out.println(resultSet.getString(2));
System.out.println(resultSet.getString(3));
}
//7.关闭资源
} catch (Exception e) {
e.printStackTrace();
}finally {
if(resultSet!=null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
DBUtil.ShutDown(statement,connection);
}
}
}
DBUtil工具类
package adil;
import java.sql.*;
public class DBUtil {
public static Connection getConnection() {
Connection connection = null;
try {
Class.forName(“com.mysql.jdbc.Driver”);
connection = DriverManager.getConnection
(“jdbc:mysql://127.0.0.1:3306/jdbc?useSSL=true&” +
“characterEncoding=utf-8&user=root&password=097510”);
// System.out.println(“创建连接成功!”);
return connection;
} catch (Exception e) {
e.printStackTrace();
}
//2.创建连接
System.out.println(“创建连接失败!”);
return null;
}
public static void ShutDown(PreparedStatement statement, Connection connection) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
Insert 添加功能类
package adil;
import java.sql.*;
public class Insert {
public static void main(String[] args){
Connection connection=null;
PreparedStatement statement=null;
//1.加载驱动
try {
Class.forName(“com.mysql.jdbc.Driver”);
//2.创建连接
connection= DBUtil.getConnection();
//3.写sql
String sql=“insert into userinfo(username,password)values(?,?)”;
//4.得到statement
statement=connection.prepareStatement(sql);
statement.setString(1,“二狗子”);
statement.setString(2,“ergouzi”);
//5.执行sql 得到结果表
statement.executeUpdate();//更新表
} catch (Exception e) {
e.printStackTrace();
}finally {
DBUtil.ShutDown(statement,connection);
}
}
}
至于Delect 删除功能类 和 Update 更新表信息功能类,基本按照Insert类中的框架,修改sql语句即可(当然可能要删改其他部分的代码),大致如下
String sql=“insert into userinfo(username,password)values(?,?)”;
修改为 String sql = “delete from userinfo where username = ‘二狗子’”;
或修改为String sql=“update userinfo set username = ‘三狗子’ where id = 3”;