JDBC连接mysql

本文介绍了使用JDBC连接MySQL数据库的详细步骤,包括在MyEclipse中创建项目,添加MySQL驱动jar包,以及编写Java代码进行连接。关键点在于根据不同的MySQL版本选择合适的驱动类,并设置时区参数以避免错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 java database connectivity:java的数据库连接,是一种数据库访问接口规范。由于数据库的种类较多,所以只需要数据库库的提供商实现底层的访问规则。

具体操作步骤:
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 驱动程序。

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值