jdbc連接數(shù)據(jù)庫(kù)實(shí)例詳解
JDBC簡(jiǎn)介
JDBC全稱(chēng)為:Java Data Base Connectivity (java數(shù)據(jù)庫(kù)連接),可以為多種數(shù)據(jù)庫(kù)提供填統(tǒng)一的訪問(wèn)。JDBC是sun開(kāi)發(fā)的一套數(shù)據(jù)庫(kù)訪問(wèn)編程接口,是一種SQL級(jí)的API。它是由java語(yǔ)言編寫(xiě)完成,所以具有很好的跨平臺(tái)特性,使用JDBC編寫(xiě)的數(shù)據(jù)庫(kù)應(yīng)用程序可以在任何支持java的平臺(tái)上運(yùn)行,而不必在不同的平臺(tái)上編寫(xiě)不同的應(yīng)用程序。
JDBC編程步驟
(1)加載驅(qū)動(dòng)程序:
下載驅(qū)動(dòng)包 : http://dev.mysql.com/downloads/connector/j/
解壓,得到 jar文件。將該文件復(fù)制到Java工程目錄Java Resources/Libraries/ 下,→ buildpath 。
(2)獲得數(shù)據(jù)庫(kù)連接
(3)創(chuàng)建Statement對(duì)象:
(4)向數(shù)據(jù)庫(kù)發(fā)送SQL命令
(5)處理數(shù)據(jù)庫(kù)的返回結(jié)果(ResultSet類(lèi))
package com.baidu.emp.jdbcTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.Driver;
/**
* 開(kāi)始使用jdbc連接數(shù)據(jù)庫(kù)
* @author Admin
*
*/
public class Test001 {
public static void main(String[] args) throws Exception {
/**
* 加載驅(qū)動(dòng)
*/
// 方法一:
/*
* import java.sql.DriverManager; import com.mysql.jdbc.Driver;
*/
// Driver driver = new Driver();
// DriverManager.registerDriver(driver);
// 方法二:(推薦使用)
Class.forName("com.mysql.jdbc.Driver");
/**
* 創(chuàng)建鏈接
*/
String url = "jdbc:mysql://localhost:3306/testjdbc";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);
// 創(chuàng)建statement對(duì)象
Statement statement = connection.createStatement();
/**
* 執(zhí)行SQL,獲取結(jié)果集
*/
String sql = "select * from test01";
ResultSet result = statement.executeQuery(sql);
// 遍歷結(jié)果集
while (result.next()) {
String name = result.getString("name");
int id = result.getInt("id");
System.out.println(name + "\t" + id);
}
/**
* 關(guān)閉鏈接,釋放資源
*/
result.close();
statement.close();
connection.close();
}
}
防止SQL注入改用prepareStatement
package com.boya.emp.jdbcTest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* SQL注入,使用prepareStatement對(duì)象進(jìn)行預(yù)編譯
* @author Admin
*
*/
public class Test002 {
public static void main(String[] args) throws Exception {
/**
* 加載驅(qū)動(dòng)
*/
Class.forName("com.mysql.jdbc.Driver");
/**
* 創(chuàng)建鏈接
*/
String url = "jdbc:mysql://localhost:3306/testjdbc";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);
// 寫(xiě)SQL
String sql = "select * from test01 where id = ?";
//創(chuàng)建statement對(duì)象,預(yù)編譯
PreparedStatement statement = connection.prepareStatement(sql);
//設(shè)置參數(shù)
statement.setInt(1, 2);
/**
* 執(zhí)行SQL,獲取結(jié)果集
*/
ResultSet result = statement.executeQuery();
// 遍歷結(jié)果集
while (result.next()) {
String name = result.getString("name");
int id = result.getInt("id");
System.out.println(name + "\t" + id);
}
/**
* 關(guān)閉鏈接,釋放資源
*/
result.close();
statement.close();
connection.close();
}
}
進(jìn)行代碼優(yōu)化,設(shè)置配置文件,工具類(lèi),實(shí)現(xiàn)增刪該查
增加配置文件方便修改數(shù)據(jù)庫(kù),用戶(hù)登錄。。。
jdbc.properties(配置文件名)
driverName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/testjdbc userName=root password=root
注意寫(xiě)配置文件時(shí)中間不可以有空格,引號(hào)之類(lèi)的
工具類(lèi):增強(qiáng)了代碼的復(fù)用性
package com.baidu.emp.utils;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.Test;
public class JdbcUtils {
static String driverClassName;
static String url;
static String user;
static String password;
static {
// 創(chuàng)建配置文件對(duì)象
Properties properties = new Properties();
// 加載配置文件輸入流
InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
// 重新加載配置文件
try {
properties.load(inputStream);
// 獲取配置文件的值
driverClassName = properties.getProperty("driverName");
url = properties.getProperty("url");
user = properties.getProperty("userName");
password = properties.getProperty("password");
Class.forName(driverClassName);
} catch (Exception e) {
// 拋出異常
throw new RuntimeException(e);
}
}
/**
* 獲取連接
*/
@Test
public void testName() throws Exception {
System.out.println(driverClassName);
}
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// 拋出異常
throw new RuntimeException(e);
}
return connection;
}
/**
* 關(guān)閉鏈接,釋放資源
*/
public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
resultSet = null; // 垃圾及時(shí)清除
//注意,不要弄成死循環(huán)
close(connection, statement);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 增刪改釋放資源
*/
public static void close(Connection connection, PreparedStatement statement) {
try {
if (connection != null) {
connection.close();
}
connection = null;
if (statement != null) {
statement.close();
}
statement = null;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
測(cè)試增刪改查:
package com.baidu.emp.jdbcTest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baidu.emp.utils.JdbcUtils;
/**
* 使用jdbcUtils連接數(shù)據(jù)庫(kù)進(jìn)行增刪改查
*
* @author Admin
*
*/
public class Test003 {
// 初始化值
Connection connection = null;
PreparedStatement statement = null;
ResultSet result = null;
@Before
public void start() throws Exception {
// 創(chuàng)建鏈接
connection = JdbcUtils.getConnection();
System.out.println("創(chuàng)建鏈接");
}
@After
public void end() throws Exception {
// 關(guān)閉鏈接
JdbcUtils.close(connection, statement, result);
System.out.println("關(guān)閉鏈接");
}
/**
*插入數(shù)據(jù)
* @throws Exception
*/
@Test
public void add() throws Exception {
String sql = "insert into test01 values(null,?)";
statement = connection.prepareStatement(sql);
statement.setString(1, "李四");
int result = statement.executeUpdate();
if (result!=0) {
System.out.println("添加成功");
}
}
/**
* 刪除數(shù)據(jù)
* @throws Exception
*/
@Test
public void del() throws Exception {
String sql = "delete from test01 where id =?";
statement = connection.prepareStatement(sql);
statement.setInt(1,3);
int result = statement.executeUpdate();
if (result!=0) {
System.out.println("刪除成功");
}
}
/**
* 修改數(shù)據(jù)
* @throws Exception
*/
@Test
public void change() throws Exception {
String sql = "update test01 set name = ? where id = ?";
statement = connection.prepareStatement(sql);
statement.setString(1, "張飛");
statement.setInt(2, 2);
int result = statement.executeUpdate();
if (result!=0) {
System.out.println("修改成功");
}
}
/**
* 查詢(xún)?nèi)繑?shù)據(jù)
* @throws Exception
*/
@Test
public void findAll() throws Exception {
String sql = "select id , name from test01";
statement = connection.prepareStatement(sql);
result = statement.executeQuery();
if (result.next()) {
System.out.println("查詢(xún)成功");
}
}
/**
* 條件查詢(xún)數(shù)據(jù)
* @throws Exception
*/
@Test
public void findOne() throws Exception {
String sql = "select id , name from test01 where id = ?";
statement = connection.prepareStatement(sql);
statement.setInt(1, 2);
result = statement.executeQuery();
if (result.next()) {
System.out.println("查詢(xún)成功");
}
}
}
以上就是相關(guān)知識(shí)以及相關(guān)代碼,感謝大家對(duì)腳本之家的支持。
相關(guān)文章
Spring Cloud如何使用Feign構(gòu)造多參數(shù)的請(qǐng)求
這篇文章主要介紹了Spring Cloud如何使用Feign構(gòu)造多參數(shù)的請(qǐng)求,以GET以及POST方法的請(qǐng)求為例進(jìn)行講解,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03
springboot如何讀取自定義properties并注入到bean中
這篇文章主要介紹了springboot讀取自定義properties并注入到bean中,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
java servlet手機(jī)app訪問(wèn)接口(一)數(shù)據(jù)加密傳輸驗(yàn)證
這篇文章主要為大家詳細(xì)介紹了java servlet手機(jī)app訪問(wèn)接口(一),數(shù)據(jù)加密傳輸驗(yàn)證,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12
IntelliJ?IDEA社區(qū)版2021.3配置SpringBoot項(xiàng)目詳細(xì)教程及失敗案例
IntelliJ?IDEA?2021.3.3是一款集成開(kāi)發(fā)環(huán)境,用于Java和其他編程語(yǔ)言的開(kāi)發(fā),下面這篇文章主要給大家介紹了關(guān)于IntelliJ?IDEA社區(qū)版2021.3配置SpringBoot項(xiàng)目詳細(xì)教程及失敗案例的相關(guān)資料,需要的朋友可以參考下2024-03-03
java 如何計(jì)算同比增長(zhǎng)工具類(lèi)
這篇文章主要介紹了java 如何計(jì)算同比增長(zhǎng)工具類(lèi)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
JAVA如何使用Math類(lèi)操作數(shù)據(jù)
這篇文章主要介紹了JAVA如何使用Math類(lèi)操作數(shù)據(jù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04

