具体操作步骤:
1.使用myeclipse新建java project项目
2.在项目中新建lib文件夹,并将Mysql-connector-java驱动包已下载的压缩包解压,将其中的jar包复制粘贴进src文件夹下。
3.右击jar包,选择Build Path-remove from Build Path
4.编写代码,在src文件夹下新建类,在.java文件中写:
package com.it.test;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.sql.Statement;
public class MainTest {
public static void main(String[] args) {
try {
//1.注册驱动
//Class.forName("com.mysql.cj.jdbc.Driver");
//DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
//2.建立连接.
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/commodities?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC", "root", "XXXXXX");
//3.创建statement,用于执行静态SQL语句并返回它所生成结果的对象
Statement st = conn.createStatement();
//4.执行查询,得到结果集
String sql ="select * from user";
ResultSet rs=st.executeQuery(sql);
//5.遍历查询每一条记录
while(rs.next()) {
int id = rs.getInt("userId");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("userId:" + id + "name:" + name + "age:" + age);
}
rs.close();
st.close();
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
注意:
<1>.mysql的版本不同,驱动也不同。mysql 6及以上使用com.mysql.cj.jdbc.Driver(),以下使用com.mysql.jdbc.Driver()
<2>.?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
JDBC连接mysql,需要制定时区servertimezone,否则会报错误:
The server time zone value '�й���ʱ��' is unrecognized or represents more than one time zone.
You must configure either the server or JDBC driver (via the serverTimezone configuration property) to
use a more specifc time zone value if you want to utilize time zone support.
所以必须加上以上代码
<3>.DriverManager.getConnection()是重载方法,可根据具体情况使用
<4>.
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());`
会形成两次注册,所以使用:
Class.forName("com.mysql.cj.jdbc.Driver");
但目前不需要上述代码也可以连接上数据库并操作,在java.sql.Drivermanage中找到信息说
Applications no longer need to explicitly load JDBC drivers using Class.forName().
Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.
应用程序不再需要使用 Class.forName() 显式地加载 JDBC 驱动程序。