日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

JDBC相关知识点

發(fā)布時間:2024/8/1 编程问答 51 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JDBC相关知识点 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

概念

java DataBase Connectivity java 數(shù)據(jù)庫連接 ,java語言操作數(shù)據(jù)庫

JDBC本質(zhì):其實(shí)是官方(sum公司)定義的一套操作所有關(guān)系類型數(shù)據(jù)庫的規(guī)則,即接口. 各個數(shù)據(jù)庫廠商去實(shí)現(xiàn)這套接口,提供數(shù)據(jù)庫驅(qū)動jar包,我們可以使用這套接口(JDBC)編程. 真正執(zhí)行的代碼是驅(qū)動jar包中的實(shí)現(xiàn)類

快速入門

public static void main(String[] args) throws ClassNotFoundException, SQLException { // 1.導(dǎo)入驅(qū)動包 mysql-connector-java-5.1.37-bin.jar // 復(fù)制mysql-connector-java-5.1.37-bin.jar到項(xiàng)目lib文件夾下(沒有可以自己創(chuàng)建) // 右鍵--> Add As Library // 2.注冊驅(qū)動Class.forName("com.mysql.jdbc.Driver"); // 3.獲取數(shù)據(jù)庫連接對象Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db3", "root", "1234"); // 4.定義sqlString sql="update account set balance =500 where id=1;"; // 5.獲取執(zhí)行sql語句對象 StatemenStatement stmt = conn.createStatement(); // 6.執(zhí)行sql,接收返回結(jié)果int count = stmt.executeUpdate(sql); // 7.處理結(jié)果System.out.println(count); // 8.釋放資源stmt.close();conn.close();} }

詳解各個對象

DriverManager:

DriverManager: 英 /?dra?v?(r)/ 英 /?m?n?d??(r)/ [拽我麥妮哲]

驅(qū)動管理對象
功能:
1.注冊驅(qū)動:告訴程序該使用哪一個數(shù)據(jù)庫驅(qū)動jar

static void registerDriver(Driver driver):注冊與給定的驅(qū)動程序 DriverManager 。寫代碼使用:class.forName("com.mysql.jdbc.Driver");通過查看源碼發(fā)現(xiàn):com.mysql.jdbc.Driver類中存在靜態(tài)代碼塊 static {try {java.sql.DriverManager.registerDriver(new Driver());}catch(SOLException E){throw new RuntimeException("Can't register driver!");}} 注意:mysql5之后的驅(qū)動jar包可以省略注冊驅(qū)動的步驟。

2.獲取數(shù)據(jù)庫連接:

方法:static connection.getconnection(string url, string user, string password) 參數(shù):url:指定連接的路徑語法:jdbc:mysql://ip地址(域名):端口號/數(shù)據(jù)庫名稱例子:jdbc:mysql://localhost:3306/db3細(xì)節(jié):如果連接的是本機(jī)mysql服務(wù)器,并且mysql服務(wù)默認(rèn)端口是3306,則url可以簡寫為:jdbc:mysql:///數(shù)據(jù)庫名稱 user:用戶名 password:密碼

Connection:

數(shù)據(jù)庫連接對象

Connection: 英 /k??nek?n/ [科 耐克神]

功能:
1.獲取執(zhí)行sql對象

Statement createStatement() PreparedStatement preparedStatement();

2.管理實(shí)務(wù)

開啟事務(wù):setAutoCommit(boolean aotuCommit):調(diào)用該方法色后置參數(shù)為false,即開啟事務(wù)提交事務(wù):commit()回滾事務(wù):rollback()

Statement:

執(zhí)行sql的對象

Statement: 英 /?ste?tm?nt/ [斯戴特悶特]

1.執(zhí)行:sql

1.boolean execute(String sql):可以執(zhí)行任意的sql(了解即可) 2.int executeUpdate(String SQL):執(zhí)行DML(insert/update/delete)語句,DDL(create/alter/drop)語句返回值:影響的行數(shù),可以通過這個影響的行數(shù)判斷語句是否執(zhí)行成功,返回值>0則成功,反之,則失敗 3.Result executeQuery(String sql):執(zhí)行DQL(select)語句

ResultSet:

結(jié)果集對象

ResultSet: 英 /r??z?lt/ [瑞饒?zhí)?賽特] next():游標(biāo)向下移動一行getXxx(): 獲取數(shù)據(jù)Xxx:代表數(shù)據(jù)類型 如:int getInt() String getString() 參數(shù):1.int :代表列的編號,1開始 比如:getString(1):獲取第一列的值注意:使用步驟1.游標(biāo)向下移動一行2.判斷是否有數(shù)據(jù)3.獲取數(shù)據(jù)//執(zhí)行sql語句rs = stat.executeQuery(sql);//循環(huán)判斷游標(biāo)是否是最后一行末尾while (rs.next()){int id = rs.getInt(1);String name = rs.getString("name");int balaance = rs.getInt(3);System.out.println(id+"==="+name+"==="+balaance);}

PreparedStatement:

執(zhí)行sql的對象

英 /pr??pe?d/ 英 /?ste?tm?nt/ [普瑞 派的 斯戴特悶特] 1,sql 注入問題:1.用戶隨便輸入密碼: a' or 'a'='a2.sql:select * from user where username ='fhdsjkf' and password = 'a' or 'a'='a'

解決方案:

public static void main(String[] args) {//鍵盤錄入姓名和密碼System.out.println("請輸入用戶名:");Scanner sc=new Scanner(System.in);String name = sc.nextLine();System.out.println("請輸入密碼:");String password = sc.nextLine();boolean flag = opinion(name, password);if (flag){System.out.println("登陸成功");}else {System.out.println("登錄失敗");}}public static boolean opinion(String name ,String password){ if (name==null||password==null){System.out.println("請檢查賬戶或者密碼");return false; }Connection conn=null;PreparedStatement pstmt=null;ResultSet rs=null;try {//使用工具類獲取connection對象conn = Utils.getConnection();String sql="select *from account where name=? and password=?;";//select *from account where name='lisi' or 1=1 and password='1234' ;//獲取Statement對象pstmt = conn.prepareStatement(sql);pstmt.setString(1,name);pstmt.setString(2,password);rs = pstmt.executeQuery();return rs.next();} catch (SQLException throwables) {throwables.printStackTrace();}finally {Utils.close(rs,pstmt,conn);}return false;}

抽取jdbc的工具類

JDBCUtils

目的:簡化書寫 分析:1.注冊驅(qū)動也抽取2.抽取一個方法獲取連接對象 需求:不想傳遞參數(shù)(麻煩那),還得保證工具類的通用性.解決:配置文件jdbc.propertiesurl=user=passwo= JDBC.properties文件:url=jdbc:mysql:///db3 user=root password=1234 driver=com.mysql.jdbc.Driver 3.抽取一個方法釋放資源

JDBC工具類:

public class Utils {private static String url;private static String user;private static String password;private static String driver;/*** 文件的讀取,只需要讀取一次即可拿到這些值,使用靜態(tài)代碼塊* */static {//讀取資源文件,獲取值try {//1.創(chuàng)建Properties集合類Properties pro = new Properties();//獲取src路徑下的文件的方式:--->ClassLoader 類加載器ClassLoader classLoader = Utils.class.getClassLoader();URL res = classLoader.getResource("jdbc.properties");String path = res.getPath();//2.加載文件pro.load(new FileReader(path));//3.獲取數(shù)據(jù),在賦值url = pro.getProperty("url");user = pro.getProperty("user");password = pro.getProperty("password");driver = pro.getProperty("driver");//4.注冊驅(qū)動Class.forName(driver);} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}}/*** 獲取連接* return連接對象**/public static Connection getConnection() throws SQLException {return DriverManager.getConnection(url, user, password);}/*** 釋放資源*/public static void close(Statement stmt, Connection conn) {if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}public static void close(ResultSet rs, Statement stmt, Connection conn) {if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}} }

測試工具類:

public class Test002 {//測試工具類public static void main(String[] args) {Connection conn=null;Statement stat=null;ResultSet rs=null;try {//使用工具類的方法conn = Utils.getConnection();//3.獲取statement對象stat = conn.createStatement();//4.定義sql語句String sql="select *from account;";//刪除account表中字段你name=wangwu的所有記錄//5.執(zhí)行sql語句rs = stat.executeQuery(sql);//6.輸出結(jié)果while (rs.next()){int id = rs.getInt(1);String name = rs.getString("name");int balaance = rs.getInt(3);System.out.println(id+"==="+name+"==="+balaance);}} catch (SQLException throwables) {throwables.printStackTrace();}finally{//釋放資源if(rs!=null){try {rs.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if(stat!=null){try {rs.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if(conn!=null){try {rs.close();} catch (SQLException throwables) {throwables.printStackTrace();}}}} }

JDBC控制事務(wù)

事務(wù):一個包含多個步驟的業(yè)務(wù)操作.如果這個業(yè)務(wù)操作被事務(wù)管理,則這個步驟要么同時成功,要么同時失敗 操作開啟事務(wù)提交事務(wù)回滾事務(wù) 使用connection對象來管理事務(wù) 開啟事務(wù):setAutoCommit(Boolean autoCommit):調(diào)用該方法設(shè)置參數(shù)為false,即為開啟事務(wù)提交事務(wù):commit()回滾事務(wù):rollback()

案例:銀行轉(zhuǎn)賬系統(tǒng)張三給李四轉(zhuǎn)賬500元,中途手動制造異常,使用事務(wù)處理

public static void main(String[] args) throws SQLException {Connection conn=null;PreparedStatement pstmt1=null;PreparedStatement pstmt2=null;try {//獲取連接conn = Utils.getConnection();//開啟事務(wù)conn.setAutoCommit(false);//false為開啟事務(wù)//定義sqlString sql1="update yinhang set money=money-? where name=?;";//定義張三-500String sql2="update yinhang set money=money+? where name=?;";//定義李四+500//獲取sql對象pstmt1 = conn.prepareStatement(sql1);pstmt2 = conn.prepareStatement(sql2);//設(shè)置參數(shù)pstmt1.setInt(1,500);pstmt1.setString(2,"zhangsan");pstmt2.setInt(1,500);pstmt2.setString(2,"lisi");pstmt1.executeUpdate();//手動制造異常int i=3/0;pstmt2.executeUpdate();//提交事務(wù)conn.commit();} catch (Exception throwables) {if(conn!=null){try {conn.rollback();} catch (SQLException e) {e.printStackTrace();}}throwables.printStackTrace();}finally {Utils.close(pstmt1,conn);Utils.close(pstmt2,null);//實(shí)際開發(fā)不能這樣寫,只為測試}}

數(shù)據(jù)庫連接池

概念 :其實(shí)就是一個容器(集合),存放數(shù)據(jù)庫連接的容器當(dāng)容器初始化好,容器被創(chuàng)建,容器中會申請一些連接對象,當(dāng)用戶來訪問數(shù)據(jù)庫時,從容器中獲取連接對象,用戶訪問完之后,會將連接對象歸還給容器; 好處:節(jié)約資源用戶訪問高效 實(shí)現(xiàn):標(biāo)準(zhǔn)接口:DataSource javax.sql包下的方法:獲取連接:getConnection()歸還連接:Connection.close().如果連接對象connection是從連接池中獲取的,那么調(diào)用Connection.close()方法則不會再關(guān)閉了,而是歸還連接.一般我們不去實(shí)現(xiàn)它,有數(shù)據(jù)庫廠商來實(shí)現(xiàn)C3P0:數(shù)據(jù)庫連接池技術(shù);Druid:數(shù)據(jù)庫連接池技術(shù),由阿里巴巴提供的

C3P0:數(shù)據(jù)庫連接池技術(shù)

步驟:
1導(dǎo)入jar包(兩個)c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar
*不要忘記導(dǎo)入數(shù)據(jù)庫驅(qū)動jar包
2.定義配文件:
*名稱:c3p0.properties或者c3p0-config.xml
* 路徑:直接將文件放在src目錄下即可。
3.創(chuàng)建核心對旅數(shù)據(jù)庫連接池對象EomboPooledDataSource
4.獲取連接:getConnection

Druid:數(shù)據(jù)庫連接池技術(shù)

步驟:
1.導(dǎo)入jar包 druid-1.0.9.jar
2.定義配文件:
*是properties形式的
可以叫任意名稱,可以放在任意目錄下
3.加載配文件。Properties
4.獲取數(shù)據(jù)庫連接池對象:通過工廠來來獲取DruidDataSourceFactory
5.獲取連接:getConnection

public static void main(String[ args) throws :Exception { //1.導(dǎo)入jar包 文件復(fù)制到lib//2.定義配文件 把properties文件復(fù)制//3.加載配置文件Properties pro = new Properties();InputStream is =DruidDemo.class.getClassLoader.getResourceAsStream( name: "druid.properties" );pro.load(is);//4.獲取連接池對象DataSource ds =DruidDataSourceFactory.createDataSource(pro);//5.獲取連接Connection conn =ds.getConnection(); System.out.println(conn);

定義一個工具類:

druid.properties文件

url=jdbc:mysql:///db3username=rootpassword=1234driverClassName=com.mysql.jdbc.DriverinitialSize=5maxActive=10maxWait=3000

定義一個類 JDBCUtils
提供靜態(tài)代碼塊加載配置文件,初始化連接池對象
提供方法
獲取連接的方法:通過數(shù)據(jù)庫連接池獲取連接
釋放資源
獲取連接池的方法

//1定義成員變量DataSourceprivate static DataSource ds;static {try {//1.加載配置文件Properties pro = new Properties();//創(chuàng)建properties屬性集對象//讀取druid.properties配置文件pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream(name:"druid.properties"));//使用druid提供的api,獲取DataSourceds = DruidDataSourceFactory.createDataSource(pro);} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}/*** 獲取連接*/public static Connection getConnection() throws SQLException {return ds.getConnection();}/*** 釋放資源* <p>* /*** 釋放資源*/public static void close(Statement stmt, Connection conn) {if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}public static void close(ResultSet rs, Statement stmt, Connection conn) {if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}public static DataSource getDataSource(){return ds;}

測試druid工具類

給account表增加一條數(shù)據(jù),添加成功則控制臺打印輸出:錄入數(shù)據(jù)的行數(shù)

public static void main(String[] args) {Connection conn = null;PreparedStatement pstmt = null;//給account表添加一條記錄try {//獲取數(shù)據(jù)conn = JDBCUtils.getConnection();//定義sqlString sql = "insert into account(ID,NAME, password) value (NULL,?,?);";//獲取PreparedStatement對象pstmt = conn.prepareStatement(sql);//給?賦值pstmt.setString(1, "zhangsan");pstmt.setInt(2, 1000);//執(zhí)行sqlint index = pstmt.executeUpdate();System.out.println(index);} catch (SQLException throwables) {throwables.printStackTrace();} finally {JDBCUtils.close(pstmt,conn);}}

總結(jié)

以上是生活随笔為你收集整理的JDBC相关知识点的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。