JDBC
简单操作JDBC
什么是JDBC?
可以执行SQL语句的Java API 第一个JDBC程序(包含JDBC书写步骤)
package com. kuang;
import java. sql. *;
public class Lesson_01 {
public static void main ( String[ ] args) throws ClassNotFoundException, SQLException {
Class. forName ( "com.mysql.jdbc.Driver" ) ;
String url= "jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&useSSL=true" ;
String username= "root" ;
String password= "123qwe" ;
Connection connection= DriverManager. getConnection ( url, username, password) ;
Statement statement= connection. createStatement ( ) ;
String sql= "SELECT * FROM app_user" ;
ResultSet resultSet= statement. executeQuery ( sql) ;
while ( resultSet. next ( ) ) {
System. out. println ( "id=" + resultSet. getObject ( "id" ) ) ;
System. out. println ( "phone=" + resultSet. getObject ( "phone" ) ) ;
}
resultSet. close ( ) ;
statement. close ( ) ;
connection. close ( ) ;
}
}
Connection对象
客户端与数据库所有的交互都是通过Connection来完成的
createcreateStatement ( )
prepareStatement ( sql)
prepareCall ( sql)
setAutoCommit ( boolean autoCommit)
commit ( )
rollback ( )
Statement对象
Statement对象用于向数据库发送Sql语句(增删改查)
executeQuery ( String sql)
executeUpdate ( String sql)
execute ( String sql)
addBatch ( String sql)
executeBatch ( )
ResultSet对象
getObject ( String columnName)
getString ( String columnName)
next ( )
Previous ( )
absolute ( int row)
beforeFirst ( )
afterLast ( )
JDBC工具类的封装
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
== == == == == == == == == == == == == == == = 文件名: db. properties== == == == == == == == == == == == == == == == == ==
== == == == == == == == == == == == == == == = 功能: 作为配置文件== == == == == == == == == == == == == == == == == == == =
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
driver= com. mysql. jdbc. Driver
url= jdbc: mysql: / / localhost: 3306 / shop? useUnicode= true & characterEncoding= utf8& useSSL= true
username= root
password= 123 qwe
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == =
== == == == == == == == == == == == == == == = 文件名: Lesson_02. java== == == == == == == == == == == == == == == == == =
== == == == == == == == == == == == == == == = 功能: 工具类== == == == == == == == == == == == == == == == == == == == == =
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
package com. kuang;
import java. io. InputStream;
import java. sql. *;
import java. util. Properties;
public class Lesson_02 {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
try {
InputStream in = Lesson_02. class . getClassLoader ( ) . getResourceAsStream ( "db.properties" ) ;
Properties properties = new Properties ( ) ;
properties. load ( in) ;
driver = properties. getProperty ( "driver" ) ;
url = properties. getProperty ( "url" ) ;
username = 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, username, 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 ( ) ;
}
}
}
}
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
== == == == == == == == == == == == == 文件名: Lesson_03. java== == == == == == == == == == == == == == == == == ==
== == == == == == == == == == == == = 功能: 使用工具类执行sql语句== == == == == == == == == == == == == == == == =
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == =
package com. kuang;
import java. sql. Connection;
import java. sql. ResultSet;
import java. sql. SQLException;
import java. sql. Statement;
public class Lesson_03 {
public static void main ( String[ ] args) {
Connection connection= null;
Statement statement= null;
ResultSet resultSet= null;
try {
connection= Lesson_02. getConnection ( ) ;
statement= connection. createStatement ( ) ;
String sql= "INSERT INTO app_user(`name`,`email`,`phone`,`gender`,`password`,`age`)" +
"VALUES('用户','2543031567@qq.com',15592621235,0,'123qwe',18);" ;
int i= statement. executeUpdate ( sql) ;
if ( i> 0 ) {
System. out. println ( "插入成功!" ) ;
}
} catch ( SQLException e) {
e. printStackTrace ( ) ;
} finally {
Lesson_02. release ( connection, statement, resultSet) ;
}
}
}
SQL注入 PreparedStatement对象与Statemenet对象的区别
1. 使用Statement对象 会产生SQL注入问题
Statement stat= connection. createStatement ( ) ;
-- 常规登录操作
resultSet= stat. executeQuery ( "select * from user where username='" + username+ "' and password='" + password+ "'" ) ;
-- sql注入操作 可以查出所有用户用户名和密码
方式一: resultSet= stat. executeQuery ( "select * from user where username='" + "' or 1=1" + "'and password='" + "' or 1=1" + "'" ) ;
方式二: resultSet= stat. executeQuery ( "select * from user where username='" + "' or 1=1 --" + "'and password='" + "' or 1=1" + "'" ) ;
2. 使用PreparedStatement对象 可以解决SQL注入问题 而且预编译 效率高
String sql= "Update Employees SET age = ? WHERE id = ?" ;
PreparedStatement pstmt= connection. preparedStatement ( sql) ;
pstmt. setInt ( 1 , 18 ) ;
pstmt. setInt ( 2 , 4 ) ;
int i= pstmt. executeUpdate ( ) ;
JDBC处理事务
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
== == == == == == == == == == == == = 文件名: Lesson_04. java== == == == == == == == == == == == == == == == == == =
== == == == == == == == == == == == = 功能: JDBC处理事务 模拟成功与失败情况== == == == == == == == == == == =
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == =
package com. kuang;
import java. sql. Connection;
import java. sql. PreparedStatement;
import java. sql. ResultSet;
import java. sql. SQLException;
public class Lesson__04 {
public static void main ( String[ ] args) {
Connection conn= null;
PreparedStatement pstmt= null;
ResultSet rs= null;
try {
conn= Lesson_02. getConnection ( ) ;
conn. setAutoCommit ( false ) ;
String sql1= "update app_user set age=age-10 where name='用户0'" ;
pstmt= conn. prepareStatement ( sql1) ;
pstmt. executeUpdate ( ) ;
String sql2= "update app_user set age=age+10 where name='用户1'" ;
pstmt= conn. prepareStatement ( sql2) ;
pstmt. executeUpdate ( ) ;
conn. commit ( ) ;
System. out. println ( "成功!" ) ;
} catch ( SQLException e) {
try {
conn. rollback ( ) ;
} catch ( SQLException ex) {
ex. printStackTrace ( ) ;
}
e. printStackTrace ( ) ;
} finally {
Lesson_02. release ( conn, pstmt, rs) ;
}
}
}
数据库连接池DBCP
什么是数据库连接池
为什么要使用数据库连接池
数据库的连接的建立和释放是非常消耗资源的 频繁地打开、关闭连接造成系统性能低下 如何编写数据库连接池 实现DataSource接口即可
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
== == == == == == == == == == == == = 文件名: dbcp. properties== == == == == == == == == == == == == == == == == ==
== == == == == == == == == == == == = 功能: 编写配置文件== == == == == == == == == == == == == == == == == == == == =
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == =
#连接设置
driverClassName= com. mysql. jdbc. Driver
url= jdbc: mysql: / / localhost: 3306 / shop? useUnicode= true & characterEncoding= utf8& useSSL= true
username= root
password= 123 qwe
#< ! -- 初始化连接 -- >
initialSize= 10
#最大连接数量
maxActive= 50
#< ! -- 最大空闲连接 -- >
maxIdle= 20
#< ! -- 最小空闲连接 -- >
minIdle= 5
#< ! -- 超时等待时间以毫秒为单位 6000 毫秒/ 1000 等于60 秒 -- >
maxWait= 60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:【属性名= property; 】
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties= useUnicode= true ; characterEncoding= UTF8
#指定由连接池所创建的连接的自动提交(auto- commit)状态。
defaultAutoCommit= true
#driver default 指定由连接池所创建的连接的只读(read- only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE, READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation= READ_UNCOMMITTED
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
== == == == == == == == == == == == = 文件名: Lesson_05. java== == == == == == == == == == == == == == == == == == =
== == == == == == == == == == == == = 功能: 编写数据库连接池== == == == == == == == == == == == == == == == == == ==
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == =
package com. kuang;
import org. apache. commons. dbcp2. BasicDataSourceFactory;
import javax. sql. DataSource;
import java. io. InputStream;
import java. sql. Connection;
import java. sql. ResultSet;
import java. sql. SQLException;
import java. sql. Statement;
import java. util. Properties;
public class Lesson_05 {
private static DataSource dataSource = null;
static {
try {
InputStream inputStream = Lesson_05. class . getClassLoader ( ) . getResourceAsStream ( "dbcp.properties" ) ;
Properties properties = new Properties ( ) ;
properties. load ( inputStream) ;
dataSource = BasicDataSourceFactory. createDataSource ( properties) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
public static Connection getConnection ( ) throws SQLException {
return dataSource. getConnection ( ) ;
}
public static void release ( Connection conn, Statement st, ResultSet rs) {
if ( rs != null) {
try {
rs. close ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
if ( st != null) {
try {
st. close ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
if ( conn != null) {
try {
conn. close ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
}
}
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
== == == == == == == == == == == == = 文件名: Lesson_06. java== == == == == == == == == == == == == == == == == == =
== == == == == == == == == == == == = 功能: 使用数据库连接池== == == == == == == == == == == == == == == == == == ==
== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == =
package com. kuang;
import java. sql. Connection;
import java. sql. ResultSet;
import java. sql. SQLException;
import java. sql. Statement;
public class Lesson_06 {
public static void main ( String[ ] args) {
Connection connection= null;
Statement statement= null;
ResultSet resultSet= null;
try {
connection= Lesson_05. getConnection ( ) ;
statement= connection. createStatement ( ) ;
String sql= "INSERT INTO app_user(`name`,`email`,`phone`,`gender`,`password`,`age`)" +
"VALUES('用户','2543031567@qq.com',15592621235,0,'123qwe',18);" ;
int i= statement. executeUpdate ( sql) ;
if ( i> 0 ) {
System. out. println ( "插入成功!" ) ;
}
} catch ( SQLException e) {
e. printStackTrace ( ) ;
} finally {
Lesson_05. release ( connection, statement, resultSet) ;
}
}
}
书写DBCP过程中遇到的问题以及解决办法
问题及解决办法
报错:Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class com.kuang.Lesson_05
解决办法:报错原因是还缺少commons-logging.jar包,导入即可 DBCP需要的3个jar包(拿走的话 记得点赞 收藏 + 关注)
mysql-connector-java-5.1.47的资源