通过JDBC操作MySQL数据库

前期准备

首先保证有一个数据库可供连接,可以是本机安装的,也可以远程连接其他计算机。

有用于操作数据库的jar包

windows安装MySQLjar包资源下载

Java操作

  • 怎样连接数据库?

//获取MySQL数据库连接驱动
String driver = "com.mysql.cj.jdbc.Driver";
//数据库连接地址
String url = "jdbc:mysql://127.0.0.1:3306/test?useSSL=FALSE&serverTimezone=UTC&characterEncoding=utf8";
//连接数据库使用的用户名和密码
String name = "root";
String password = "123456";
try {
	//加载驱动程序
	Class.forName(driver);
	//打开数据库连接
	connection = DriverManager.getConnection(url, name, password);
} catch (ClassNotFoundException e) {
	e.printStackTrace();
} catch (SQLException e) {
	e.printStackTrace();
}

 通过 com.mysql.cj.jdbc.Driver 可以将驱动指向MySQL。(MySQL5.7之前的数据库版本驱动名是com.mysql.jdbc.Driver)

加载驱动之后,通过DriverManager类的getConnection()方法就可以创建一个连接,创建连接的时候需要指定要连接的数据库的位置,用户名以及连接密码。其中url = "jdbc:mysql://127.0.0.1:3306/test?useSSL=FALSE&serverTimezone=UTC&characterEncoding=utf8";指明了要连接的数据库是MySQL,本机3306端口,数据库名是test,不使用userSSL,使用UTC(国际标准时间)为服务器时区,字符集设置为utf-8,使用root这个用户权限连接,root用户的连接密码是123456.

如果连接的不是本机的数据库,需要将127.0.0.1(或者localhost)更换为数据库所在主机的IP地址,用户名和密码根据实际情况做相应的改变。

useSSL=FALSE&serverTimezone=UTC在低版本的数据库中不需要设置,时区的设置我一直使用UTC也并没有遇到和本地时间不符的问题。

如果数据库存储的信息中有中文字符,尽量设置字符集characterEncoding=utf8以免出现中文字符无法正常解析的问题。

  • 如何通过SQL操作数据库?

//创建数据库操作对象
Statement statement = connection.createStatement();
//对数据库进行更新
statement.executeUpdate(sqlUpdateCommand);
//对数据库进行查询 并将查询的到的结果集保存并返回
ResultSet resultSet = statement.executeQuery(sqlSelectCommand);

通过createStatement()方法可以创建一个Statement对象,statement对象可以发送SQL命令。

一般情况下,对数据库的数据操作就是增删改查四种类型。除了查询需要返回查询得到的结果集之外,增删改都属于更新操作。

数据库静态操作使用Statement很方便,但是对于动态SQL命令,使用Statement存在SQL注入的风险,建议使用具有预编译功能的PrepareStatement。但是本次为了演示结构清晰,全部使用Statement。如果读者有兴趣,可以参看SQL注入原理演示了解PrepareStatement的使用方法和PrepareStatement是如何防范SQL注入。

  • 如何遍历查询得到的结果集?

假设查询是 ResultSet rs = statement.executeQuery("select sno,name,classes,score from student");

try {
    while(rs.next()) {
	String sno = rs.getString("sno");
        String name = rs.getString("name");
        String classes = rs.getString("classes");
        double score = rs.getDouble("score");
        System.out.println(sno + "#" + name + "#" + classes + "#" + score);
    }
} catch (SQLException e) {
	e.printStackTrace();
}
  • 程序样例

package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
* @ClassName: DataBaseUtil
* @Description: 数据库连接 操作 关闭方法
* @author 码途有约
* @date 2018年11月15日
*/
public class DataBaseUtil {
	/**
	 * 用于创建数据库连接的Connection对象
	 * 用于发送SQL指令的Statement对象
	 * 用于保存数据库结果的ResultSet对象
	 */
	Connection connection = null;
	Statement statement = null;
	ResultSet resultSet = null;
	
	/**
	 * 
	* @Title: getConnection
	* @Description: 获取数据库连接
	* @return 数据库连接接口
	 */
	public Connection getConnection() {
		//获取MySQL数据库连接驱动
		String driver = "com.mysql.cj.jdbc.Driver";
		//数据库连接地址
		String url = "jdbc:mysql://127.0.0.1:3306/test?useSSL=FALSE&serverTimezone=UTC&characterEncoding=utf8";
		//连接数据库使用的用户名和密码
		String name = "root";
		String password = "123456";
		try {
			//加载驱动程序
			Class.forName(driver);
			//打开数据库连接
			connection = DriverManager.getConnection(url, name, password);
			return connection;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 
	* @Title: update
	* @Description: 完成数据库的数据更新操作 即数据库的增删改
	* @param sqlCommand 数据更新操作的SQL命令
	 */
	public void update(String sqlCommand) {
		if(connection == null) {
			//在未创建连接的时候新建一个连接
			connection = getConnection();
		}
		try {
			//创建数据库操作对象
			statement = connection.createStatement();
			//对数据库进行更新
			statement.executeUpdate(sqlCommand);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	* @Title: select
	* @Description: 数据库查询操作
	* @param sqlCommand 数据库查询语句
	* @return 返回从数据库查询得到的结果集
	 */
	public ResultSet select(String sqlCommand) {
		if(connection == null) {
			//在未创建连接的时候新建一个连接
			connection = getConnection();
		}
		try {
			//创建数据库操作对象
			statement = connection.createStatement();
			//对数据库进行查询 并将查询的到的结果集保存并返回
			resultSet = statement.executeQuery(sqlCommand);
			return resultSet;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 
	* @Title: close
	* @Description: 关闭数据库连接并释放相关资源
	 */
	public void close() {
		//仅在有连接或者资源被占用时进行关闭
		try {
			if(connection != null) {
				connection.close();
			}
			if(statement != null) {
				statement.close();
			}
			if(resultSet != null) {
				resultSet.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
package util;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
* @ClassName: DataBaseTest
* @Description: 
* @author 码途有约
* @date 2018年11月17日
*/
public class DataBaseTest {
	public static void main(String[] args) {
		DataBaseUtil util = new DataBaseUtil();
		String sql = "select sno,name,classes,score from student";
		ResultSet rs = util.select(sql);
		try {
		    while(rs.next()) {
			String sno = rs.getString("sno");
		        String name = rs.getString("name");
		        String classes = rs.getString("classes");
		        double score = rs.getDouble("score");
		        System.out.println(sno + "#" + name + "#" + classes + "#" + score);
		    }
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			util.close();
		}
	}
}

笔者个人倾向于将close()方法放在 finally 当中,防止数据库操作过程当中发生异常导致资源没有释放。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值