JDBC(Java数据库连接,java数据库连接)是一种用于执行SQL语句的Java API,JDBC编程前提是需要放入对应数据库类型的jar文件驱动,在这里我使用的数据库是my sql,所以使用对应版本的jar包。
导入jar包的具体步骤如下:
1.首先新建一个目录,再将下载的驱动包放入里面。(驱动包可以在官网下载)
2.之后右键该驱动包–>选择add as library选项。
之后是具体的程序:
import java.sql.*;
import java.sql.SQLException;
public class JDBC {
public static void main(String[] args) {
ResultSet resultSet = null;
PreparedStatement statement1 = null;
PreparedStatement statement2 = null;
Connection connection = null;
try {
connection=Connect.connect();
System.out.println("创建连接成功");
String sql1="insert into user(id,username,password) value(?,?,?)";
statement1=connection.prepareStatement(sql1);
statement1.setInt(1,4);
statement1.setString(2,"123321");
statement1.setString(3,"123456");
statement1.executeUpdate();
String sql2="select * from user";
statement2=connection.prepareStatement(sql2);
resultSet=statement2.executeQuery();
while(resultSet.next()) {
System.out.println(resultSet.getInt(1));
System.out.println(resultSet.getString(2));
System.out.println(resultSet.getString(3));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(resultSet != null){ //关闭resultSet
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(statement1 != null){ //关闭statement1
try {
statement1.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int x = 1;
x = CloseFunction.Closefunc(connection);
if(x == 0){
System.out.println("断开连接");
}
}