JAVA:JDBC连接MySQL数据库
程序员文章站
2024-03-13 19:01:57
...
一、下载mysql连接包,放到项目中
a) 首先要到mysql官网下载Connector/J地址是:
http://www.mysql.com/downloads/connector/j/
b) 解压后的文件夹是:
c) 拷贝到工程中:
d) 鼠标右键:Add to Build Path
二、新建一个DBHelper类用来打开或关闭数据库:
package com.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DBHelper {
public static final String url = "jdbc:mysql://127.0.0.1/xxxxx";
public static final String name = "com.mysql.jdbc.Driver";
public static final String user = "root";
public static final String password = "123456";
public Connection conn = null;
public PreparedStatement pst = null;
public DBHelper(String sql) {
try {
Class.forName(name);// 指定连接类型
conn = DriverManager.getConnection(url, user, password);// 获取连接
pst = conn.prepareStatement(sql);// 准备执行语句
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
this.conn.close();
this.pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
三、新建一个HelloJDBC类用来执行查询操作:
package com.db;
import java.sql.ResultSet;
import java.sql.SQLException;
public class HelloJDBC {
static String sql = null;
static DBHelper db1 = null;
static ResultSet ret = null;
public void query() {
sql = " select * from zduser ";//SQL语句
db1 = new DBHelper(sql);//创建DBHelper对象
try {
ret = db1.pst.executeQuery();//执行语句,得到结果集
while (ret.next()) {
String uid = ret.getString(1);
String ufname = ret.getString(2);
String ulname = ret.getString(3);
String udate = ret.getString(4);
System.out.println(uid + "\t" + ufname + "\t" + ulname + "\t" + udate );
}//显示数据
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
ret.close();
db1.close();//关闭连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
四、执行main方法报错了
a) 错误信息:com/mysql/jdbc/Driver : Unsupported major.minor version 52.0
b) 原因:是因为我的jdk和mysql提供的jar包不匹配,重新下载一个mysql连接jar包,如图:
替换即可。
五、重新运行main程序,执行正确。