java jdbc6_Java学习-JDBC

JDBC

1、数据库驱动

应用程序通过驱动连接到数据库,进而操作数据库。

2、JDBC

简化开发人员对数据库的操作,提供了一个java操作数据库的规范,俗称JDBC

对于程序猿,只需要学习JDBC提供的接口。

java.sql

javax.sqlpublic class DemoJdbc01 {

public static void main(String[] args) throws ClassNotFoundException, SQLException {

//1.加载驱动

Class.forName("com.mysql.cj.jdbc.Driver");

//2.连接 用户信息和url

String url = "jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true";

String username = "root";

String password = "handhand";

//3.连接成功,数据库对象 Connection代表数据库

Connection connection = DriverManager.getConnection(url, username, password);

//4.执行SQL的对象 Statement

Statement statement = connection.createStatement();

//5.执行SQL的对象 去 执行SQL,可能存在结果。

String sql = "select * from users";

//返回的结果集

ResultSet resultSet = statement.executeQuery(sql);

while (resultSet.next()) {

System.out.println("id" + resultSet.getObject("id"));

System.out.println("name" + resultSet.getObject("name"));

System.out.println("password" + resultSet.getObject("password"));

System.out.println("email" + resultSet.getObject("email"));

System.out.println("dirthday" + resultSet.getObject("dirthday"));

}

//6.释放连接

resultSet.close();

statement.close();

connection.close();

}

}加载驱动

连接数据库 DriverManager

获得执行sql的对象 Statement

获得返回的结果集

释放连接URLString url = "jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true";

//mysql -- 3306

//jdbc:mysql://主机地址:端口号/数据库名?参数1&参数2

//oracle -- 1521

//jdbc:oracle:thin:@主机地址:端口号:sidDriverManagerConnection connection = DriverManager.getConnection(url, username, password);

//connection 代表数据库,可以做数据库的操作

//数据库设置自动提交

connection.getAutoCommit();

//事务提交

connection.commit();

//事务回滚

connection.rollback();Statement   PrepareStatement 执行SQL的对象statement.executeQuery();//查询操作  返回ResultSet

statement.executeUpdate(); //执行任何sql

statement.execute();//更新、插入、删除,返回受影响的行数ResultSet 查询的结果集:封装了所有的查询结果//在不知道列类型的情况下使用getObject,否则使用指定的类型

resultSet.getObject();

resultSet.getString();

resultSet.getInt();

resultSet.getFloat();

resultSet.getDate();

...

遍历//移动到最前面

resultSet.beforeFirst();

//移动到最后面

resultSet.afterLast();

//移动到下一个

resultSet.next();

//移动到前一行

resultSet.previous();

//移动到指定行

resultSet.absolute(row);释放资源resultSet.close();

statement.close();

connection.close();

3、Statement对象

执行SQL的对象 Statement

Statement statement = connection.createStatement();CRUD操作-create

使用executeUpdate(String sql)方法完成数据添加操作:String sqlCreate = "INSERT INTO users VALUES ( 4, 'test', '134513', 'z13@131.com', '1995-01-01')";

int num = statement.executeUpdate(sqlCreate);

if (num > 0) {

System.out.println("插入数据成功");

}CRUD操作-update

使用executeUpdate(String sql)方法完成数据更新操作:String sqlUpdate = "UPDATE users u \n" +

"SET s.NAME = 'test02' \n" +

"WHERE\n" +

"\ts.id = 4";

int num = statement.executeUpdate(sqlUpdate);

if (num > 0) {

System.out.println("更新数据成功");

}CRUD操作-delete

使用executeUpdate(String sql)方法完成数据删除操作:String sqlDelete="DELETE \n" +

"FROM\n" +

"\tusers u \n" +

"WHERE\n" +

"\tu.id = 4";

int num = statement.executeUpdate(sqlDelete);

if (num > 0) {

System.out.println("插入删除成功");

}CRUD操作-read

使用executeQuery(String sql)方法完成数据查询操作:String sql = "select * from users";

//返回的结果集

ResultSet resultSet = statement.executeQuery(sql);

while (resultSet.next()) {

}

创建utils工具类public class JdbcUtils {

private static String driver = null;

private static String url = null;

private static String name = null;

private static String password = null;

static {

try {

InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");

Properties properties = new Properties();

properties.load(in);

//读取properties文件定义的参数值

driver = properties.getProperty("driver");

url = properties.getProperty("url");

name = properties.getProperty("username");

password = properties.getProperty("password");

//驱动加载,只需要一次

Class.forName(driver);

} catch (Exception e) {

e.printStackTrace();

}

}

//获取连接

public static Connection getConnection() throws SQLException {

return DriverManager.getConnection(url, name, password);

}

public static void release(Connection connection, Statement statement, ResultSet resultSet) {

if (resultSet != null) {

try {

resultSet.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (statement != null) {

try {

statement.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (connection != null) {

try {

connection.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

调用 utils工具类public class DemoInsert {

public static void main(String[] args) throws SQLException {

Connection connection = JdbcUtils.getConnection();

Statement statement = connection.createStatement();

String sql = "INSERT INTO users\n" +

"VALUES\n" +

"\t( 4, 'darj453o', '14534513', 'z13@133451.com', '1995-01-01' )";

int i = statement.executeUpdate(sql);

if (i>0){

System.out.println("插入成功");

}

JdbcUtils.release(connection,statement,null);

}

}

4、PreparedStatement对象

PreparedStatement 使用?占位符

防止SQL注入的本质,传递进来的参数当做字符public class DemoUpdate {

public static void main(String[] args) throws SQLException {

Connection connection = JdbcUtils.getConnection();

//区别Statement

//使用?占位符

String sql = "UPDATE users s \n" +

"SET s.NAME = ?,\n" +

"s.dirthday = ? \n" +

"WHERE\n" +

"\ts.id = ?";

//预编译sql

PreparedStatement preparedStatement = connection.prepareStatement(sql);

//手动赋值

preparedStatement.setString(1, "test02");

//sql.Date 数据库 java.sql.Date()

//util.Date Java  new Date().getTime()

preparedStatement.setDate(2, new java.sql.Date(System.currentTimeMillis()));

preparedStatement.setInt(3, 4);

//执行

int i = preparedStatement.executeUpdate();

if (i > 0) {

System.out.println("更新成功");

}

JdbcUtils.release(connection, preparedStatement, null);

}

}

5、事务ACID原则

原子性:要哦全部完成,要么都不完成

一致性:总数不变

隔离性:多个进程互不干扰。存在以下问题脏读:一个事务读取了另一个没有提交的事务

不可重复读:在同一个事务内,重复读取表中的数据,表数据发生了改变

虚读:在一个事务内,读取到了别人插入的数据,导致前后读出来的结果不一致

持久性:一旦提交不可逆,持久化到数据库

6、数据库连接池

数据库执行步骤:数据库连接 --- 执行完毕 --- 释放

池化技术:准备一些预先的资源,过来就连接准备好的

连接池常用的参数最小连接数:10

最大连接数: 100  业务最高承载上限

等待超时:100ms

编写连接池,需要实现一个接口 DateSource开源数据源实现

DBCP

C3P0

Druid

使用这些连接池之后,可以节省连接数据库的代码Connection connection = JdbcUtils.getConnection();DBCP

需要用到的jar包:commons-dbcp-1.4.jar、commons-pool-1.6.jar配置文件#连接设置

driverClassName=com.mysql.cj.jdbc.Driver

url=jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true

username=root

password=handhand

#初始化连接

initialSize=10

#最大连接数

maxActive=50

#最大空闲连接

maxIdle=20

#最小空闲连接

minIdle=5

#超时等待 以毫秒为单位

maxWait=60000

#JBDC驱动建立连接是负载的连接属性的格式必须为:[属性名=property;]

#注意:“” 两个属性会被明确的传递,因此这里不需要包含他们

connectionProperties=userUnicode=true;characterEncoding=utf8

#指定有连接池锁创建的连接的自动提交状态(auto-commit)状态

defaultAutoCommit=true

#driver default 指定由连接池所创建的连接的只读(read-only)状态

defaultReadOnly = false

#driver default 指定指定由连接池所创建的连接的事物级别(TransactionIsolation)

defaultTransactionIsolation=READ_UNCOMMITTED

工具类public class JdbcUtilsDbcp {

private static DataSource dataSource = null;

static {

try {

InputStream in = JdbcUtilsDbcp.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");

Properties properties = new Properties();

properties.load(in);

//创建数据源 工厂模式

dataSource = BasicDataSourceFactory.createDataSource(properties);

} catch (Exception e) {

e.printStackTrace();

}

}

//获取连接

public static Connection getConnection() throws SQLException {

return dataSource.getConnection();

}

public static void release(Connection connection, Statement statement, ResultSet resultSet) {

if (resultSet != null) {

try {

resultSet.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (statement != null) {

try {

statement.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (connection != null) {

try {

connection.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}C3P0

需要用到的jar包:mchange-commons-java-0.2.20.jar、c3p0-0.9.5.5.jar配置文件 c3p0-config.xml<?xml  version="1.0" encoding="UTF-8" ?>

com.mysql.cj.jdbc.Driver

jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true

root

handhand

5

10

60000

com.mysql.cj.jdbc.Driver

jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true

root

handhand

5

8

60000

工具类public class JdbcUtilsC3P0 {

private static ComboPooledDataSource dataSource = null;

static {

try {

//创建数据源

dataSource = new ComboPooledDataSource("Darker");

} catch (Exception e) {

e.printStackTrace();

}

}

//获取连接

public static Connection getConnection() throws SQLException {

return dataSource.getConnection();

}

public static void release(Connection connection, Statement statement, ResultSet resultSet) {

if (resultSet != null) {

try {

resultSet.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (statement != null) {

try {

statement.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if (connection != null) {

try {

connection.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/408984.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Unity3D For Android 开发教程【转http://game.ceeger.com/Unity/Doc/2011/Unity3D_For_Android.html】...

Unity3D For Android 开发教程 Date:2011-08-01 04:33我自认为抵挡诱惑的能力还是很强大的&#xff0c;关键的时候还能把持住自己。今天逛了一下南京的丹凤街&#xff0c;终于受不住Android这美眉的诱惑。她虽脸蛋不怎么滴&#xff0c;但身材火热&#xff0c;且性感&#xff0c…

剑指offer--二进制中1的个数

记录来自《剑指offer》上的算法题。 题目如下&#xff1a; 请实现一个函数&#xff0c;输入一个整数&#xff0c;输出该数二进制表示中1的个数。例如把9表示成二进制是1001&#xff0c;有两位是1&#xff0c;因此如果输入9&#xff0c;函数输出是2。 这道题目的一个基本思路是…

CentOS 6.4 编译安装 gcc-4.8.0

1.首先下载源代码 wget http://ftp.gnu.org/gnu/gcc/gcc-4.8.0/gcc-4.8.0.tar.bz22.解压 tar -jxvf gcc-4.8.0.tar.bz23.下载编译所需的依赖项 cd gcc-4.8.0  ./contrib/download_prerequisites  cd ..4.建立编译输出目录 mkdir gcc-build-4.8.05.进入此目录&#xff0c;执…

剑指offer--数值的整数次方

记录来自《剑指offer》上的算法题。 题目描述&#xff1a; 实现函数 double Power(double base, int exponent), 求 base的 exponent次方。不得使用库函数&#xff0c;同时不需要考虑大数问题。 下面是一种解法&#xff1a; // 判断num1是否等于num2 bool equal(double num1,…

jackson java网络接口_java~jackson实现接口的反序列化

jackson是springboot中集成的序列化方式&#xff0c;是默认的json序列化方式&#xff0c;当然你可以使用其它的序列化工具代替它&#xff0c;不过今天我们还是说一下它&#xff0c;使用jackson进行序列化一个类&#xff0c;然后再把它的JSON字符反序列化为它的接口对象。现实这…

剑指offer--打印1到最大的n位数

记录来自《剑指offer》上的算法题。 题目如下&#xff1a; 输入数字n&#xff0c;按顺序打印出从1到最大的n位十进制数。比如输入3&#xff0c;则打印出1&#xff0c;2&#xff0c;3一直到最大的3位数即999。 第一种解法是比较容易想到&#xff0c;但是遇到大数问题的时候会有…

java判断闰年通过多态方法_04748《Java语言程序设计》实验指导书.doc

04748《Java语言程序设计》实验指导书.docJava语言程序设计实验指导书前言一、上机实验目的上机实验的目的是提高学生的分析问题、解决问题的能力和动手能力&#xff0c;通过实践环节理解 Java语言的基本结构和程序设计方法。通过亲手编程掌握 Java 程序设计编程的方法。二、实…

利用宏定义在编译阶段检查结构体大小的方法

http://blog.csdn.net/crazycoder8848/article/details/8292770 typedef struct {char a[100]; } T_XXX;typedef struct {char a[99]; } T_QQQ;/* 检测结构体的大小是否等于特定值 */ #define SIZE_OF_TYPE_EQUAL_TO(type, size) \ static inline char size_of_##type##_eq…

剑指offer--在O(1)时间内删除链表结点

记录来自《剑指offer》上的算法题。 题目如下&#xff1a; 给定单向链表的头指针和一个结点指针&#xff0c;定义一个函数在O(1)时间删除该结点。 结点定义如下&#xff1a; struct ListNode{int m_nValue;ListNode* m_pNext; }; 最常规的删除链表结点方法是从头结点开始遍历…

Designer设计无代码工作流

1. 打开Designer&#xff0c;选择工作流&#xff0c;选择列表工作流&#xff0c;选择你要将此工作流应用的列表&#xff08;这里我选择报销单&#xff09;。 填写好工作流名称&#xff0c;点击确定。 现在我们开始正式设计工作流&#xff0c;首先我们拉一个记录历史到工作流中&…

剑指offer--调整数组顺序使奇数位于偶数前面

记录来自《剑指offer》的算法题。 题目如下&#xff1a; 输入一个整数数组&#xff0c;实现一个函数来调整该数组中数字的顺序&#xff0c;使得所有奇数位于数组的前半部分&#xff0c;所有偶数位于数组的后半部分。 最简单的思路就是从头开始扫描整个数组&#xff0c;当碰到偶…

java proguard 使用_使用proguard混淆java9代码

序本文主要研究一下如何使用proguard混淆java9代码mavencom.github.wvengenproguard-maven-pluginpackageproguard6.0.1${project.build.finalName}.jar${project.build.finalName}.jar!META-INF/maven/**,!module-info.classtrue${project.basedir}/proguard.cfg${java.home}/…

75个移动App开发教程

原文地址&#xff1a;http://www.goodfav.com/zh/app-development-tutorials-3559.html 移动应用程序开发是大企业和创意的个人和小团队开发&#xff0c;是一个有很多商业机会的领域之一。它可能需要多次尝试设计来实施一个出类拔萃的应用程序&#xff0c;但是&#xff0c;如果…