前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JDBC干货一

JDBC干货一

作者头像
爱撒谎的男孩
发布2019-12-31 14:41:17
4630
发布2019-12-31 14:41:17
举报
文章被收录于专栏:码猿技术专栏码猿技术专栏

文章目录

  1. 1. JDBC
    1. 1.1. 什么是JDBC
    2. 1.2. 为什么使用JDBC
    3. 1.3. eclipse配置maven
    4. 1.4. 如何使用JDBC
    5. 1.5. 执行方法(Statement)
    6. 1.6. ResultSet(查询得到结果集)
    7. 1.7. 关闭资源(close)
    8. 1.8. 关闭顺序
    9. 1.9. 异常处理
    10. 1.10. JDBC封装

JDBC

什么是JDBC

  • Java Database Connectivity
  • JDBC是java中一套和数据库进行交互的API(应用程序编程接口)

为什么使用JDBC

  • 因为java程序猿需要连接各种数据库(oracle,mysql,db2等)为了避免java程序猿每一种数据库都需要学习一遍,sun公司提出一个JDBC接口,各个数据库厂商去针对此接口写实现类(数据库驱动),这样的话java程序猿连接数据库只需要掌握JDBC接口的调用就可以操作各种数据库

eclipse配置maven

  1. 本机安装maven
  2. 修改远程仓库地址
    • maven的配置文件settings中修改
<?xml version="1.0" encoding="UTF-8"?>
    <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
	    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	    xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
	<pluginGroups>
	</pluginGroups>
	<proxies>
	</proxies>
	<servers>
	</servers>
	<mirrors>
		<mirror>
			<id>nexus</id>
			<name>Tedu Maven</name>
			<mirrorOf>*</mirrorOf>
			<!--<url>http://maven.tedu.cn/nexus/content/groups/public</url>-->
			 <url>http://maven.aliyun.com/nexus/content/groups/public/</url> 
		</mirror>
	</mirrors>
	<profiles>
	</profiles>
	<activeProfiles>
	</activeProfiles>
</settings>

  1. 在eclispe中配置
    • window —- > perferences —- > Maven — > User Settings —- > 在Global Settings中选择你的maven配置文件settings即可
    • OK
  2. 新建项目
    • New — > Maven Project — > Create Simple Project
    • 第一次创建可能需要很长的时间
  3. 在pom.xml中写上依赖
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cn.tedu</groupId>
  <artifactId>JDBCMaven</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.44</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.3.7.RELEASE</version>
		</dependency>
	</dependencies>  
</project>

如何使用JDBC

  • 创建maven工程
  • 下载mysql相关jar包
  • 登录阿里私服: maven.aliyun.cn

执行方法(Statement)

  • execute(sql) 执行DDL create alter
  • executeUpdate(sql) 执行DML insert update delete
  • executeQuery(sql) 执行select语句
      Class.forName("com.mysql.jdbc.Driver");   //注册驱动
//链接数据库
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "root");
//创建Statement,执行sql语句的对象
Statement statement =connection.createStatement();

String sql_create="create table if not exists t(id int primary key auto_increment,age int ,name varchar(10))";

String sql_insert="insert into t(age,name) values(22,'jack'),(33,'tom')";

String sql_sselect="select * from t";
//执行create 语句
Boolean flag=statement.execute(sql_create);
System.out.println(flag);
//执行insert语句
int row=statement.executeUpdate(sql_insert);
System.out.println(row);
//执行select
ResultSet resultSet=statement.executeQuery(sql_sselect);
while(resultSet.next()){
	int id=resultSet.getInt("id");
	int age=resultSet.getInt("age");
	String name = resultSet.getString("name");
	System.out.println(id+"----"+age+"----"+name);
}

ResultSet(查询得到结果集)

  • 代表查询语句得到的结果集(executeQuery)
  • 见到resultSet 就用while
  • next() 移动游标 有下一条返回true,没有返回false
      Class.forName("com.mysql.jdbc.Driver");  //加载驱动
      
      // 链接数据库
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root", "root");
Statement statement =connection.createStatement();   //获取执行sql语句对象
      String sql_sselect="select * from t";   //创建sql语句
      ResultSet resultSet=statement.executeQuery(sql_sselect);  //获取结果集

while(resultSet.next()){
	int id=resultSet.getInt("id");
	int age=resultSet.getInt("age");
	String name = resultSet.getString("name");
	System.out.println(id+"----"+age+"----"+name);
}

关闭资源(close)

  • 关闭Connection
    • 如果sql执行完,继续持有连接没有意义,会造成服务器压力过大,所以需要关闭
  • 关闭Statement
    • 会占用内存的资源,所以用完就关闭
  • 关闭ResultSet
    • 因为ResultSet对象中包含查询结果的数据,会占用内存空间

关闭顺序

  • ResultSet , Statement , Connection

异常处理

@Test
	public void testException() {
		Connection connection = null;  //申明Connection为null
		Statement statement = null;   // 申明 Statement为null
		try {
			Class.forName("com.mysql.jdbc.Driver"); // 注册驱动
			// 链接数据库
			connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/jdbc", "root", "root");
			// 创建Statement,执行sql语句的对象
			statement = connection.createStatement();
			String sql_insert = "insert into t(age,name) values(22,'marry'),(33,'Alice')";
			int row=statement.executeUpdate(sql_insert);
			System.out.println(row);

		} catch (Exception e) {
			System.out.println("出异常");
			e.printStackTrace();

		} finally {
			if (statement != null) {
				try {
					statement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

JDBC封装

  • 目的:把频繁出现的代码封装起来,起到代码复用的作用,从而提高开发效率
  1. 创建DBUtils类(数据库工具类)
    1. 封装建立数据连接
    2. 封装关闭资源
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库封装类
 * @author chenjiabing
 */
public class DBUtils {
	/**
	 * 获取连接对象
	 * @param user  数据库用户名
	 * @param password 密码
	 * @param database : 数据库名称
	 */
	public static Connection getConnection(String user, String password,
			String database) throws Exception {
		Class.forName("com.mysql.jdbc.Driver"); // 注册驱动
		// 链接数据库
		Connection connection = DriverManager.getConnection(
				"jdbc:mysql://localhost:3306/" + database, user, password);
		return connection;
	}

	/**
	 * 关闭数据库资源
	 * @param connection 连接对象
	 * @param statement Statement对象
	 * @param resultSet 结果集
	 */
	public static void close(Connection connection, Statement statement,
			ResultSet resultSet) {
		try {
			if (resultSet != null) {
				resultSet.close();
			}

			if (statement != null) {
				statement.close();
			}

			if (connection != null) {
				connection.close();
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}

	}

}
  1. 测试
   @Test
public void testUntils(){
	Connection connection=null;
	Statement statement=null;
	ResultSet resultSet=null;
	try {
		 connection=DBUtils.getConnection("root", "root", "jdbc");  //获取连接
		 statement=connection.createStatement();
		 //插入数据
		 int row = statement.executeUpdate("insert into t(age,name) values(22,'陈加兵'),(33,'Jackson')");
		 System.out.println(row);
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		DBUtils.close(connection, statement, resultSet);
	}
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-03-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • JDBC
    • 什么是JDBC
      • 为什么使用JDBC
        • eclipse配置maven
          • 如何使用JDBC
            • 执行方法(Statement)
              • ResultSet(查询得到结果集)
                • 关闭资源(close)
                  • 关闭顺序
                    • 异常处理
                      • JDBC封装
                      相关产品与服务
                      云数据库 SQL Server
                      腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
                      领券
                      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档