在IDEA使用JDBC连接数据库
在maven的pom.xml中导入依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
刷新maven项目,待项目中下载完mysql-connector的jar文件.
在项目中创建一个JDBCDeamo类
import java.sql.*;
/**
* @Deacription TODO
* @Author d1252
* @Date 2021/5/19 15:08
**/
public class JDBCDemo1 {
private String user = null;
private String password = null;
private String Driver = null;
Connection conn = null;
Statement state = null;
ResultSet rs = null;
public void getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
if (conn == null) {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "12345678");
System.out.println("连接数据库成功");
state = conn.createStatement();
int count = 0;
rs = state.executeQuery("select * from studentinfo");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
Boolean gender = rs.getBoolean("gender");
Date birthday = rs.getDate("birthday");
System.out.println("序号:" + id + "\t名称:" + name + "\t性别:" + gender + "\t生日:" + birthday
);
}
}
}
public void closeAll() throws SQLException {
if (rs!=null){
rs.close();
}
if (state != null) {
state.close();
}
if (conn != null) {
conn.close();
}
System.out.println("释放资源成功!");
}
public static void main(String[] args) throws SQLException, ClassNotFoundException {
JDBCDemo1 jdbcDemo1 = new JDBCDemo1();
jdbcDemo1.getConnection();
jdbcDemo1.closeAll();
}
}
连接数据库成功
序号:1 名称:孙悟空 生日:1993-03-24
序号:2 名称:白骨精 生日:1995-03-24
序号:3 名称:猪八戒 生日:1903-03-08
序号:4 名称:孙悟空 生日:1993-03-24
序号:5 名称:黑熊怪 生日:1999-03-23
序号:6 名称:黑熊怪 生日:1999-03-23
序号:7 名称:白龙马 生日:1994-01-21
序号:8 名称:白龙马 生日:1994-01-21
序号:9 名称:白龙马 生日:1994-01-21
序号:10 名称:白龙马 生日:1994-01-21
序号:12 名称:白龙马 生日:1994-01-21
序号:13 名称:白龙马 生日:1994-01-21
序号:14 名称:白龙马 生日:1994-01-21
释放资源成功!
Process finished with exit code 0
值得注意的是高版本的mysql-connector-java jar文件,在JDBC中的Driver变量值为"com.mysql.cj.jdbc.Driver",低版本比如mysql-connector-java:5.1.25则是上述"com.mysql.jdbc.Driver"
如果非Maven管理项目的,可在项目构造Project Structure中导入mysql的jar包,并且在此处也可以管理项目中导入jar包的版本
File>>>Project Structure 或者Shift+Alt+Ctrl+S打开