生活随笔
收集整理的這篇文章主要介紹了
java 连接mysql 并测试是否成功
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
java 連接MySQL 并測試是否成功。
?
[html] view plaincopy
package?com.test.tool;????import?java.sql.Connection;??import?java.sql.DriverManager;??import?java.sql.PreparedStatement;??import?java.sql.ResultSet;??import?java.sql.SQLException;??import?java.sql.Statement;??????public?class?JDBCUtlTool?{??????public?static?Connection?getConnection(){??????????String?driver="com.mysql.jdbc.Driver";???//獲取mysql數據庫的驅動類??????????String?url="jdbc:mysql://localhost:3306/test";?//連接數據庫(kucun是數據庫名)??????????String?name="root";//連接mysql的用戶名??????????String?pwd="123456";//連接mysql的密碼??????????try{??????????????Class.forName(driver);??????????????Connection?conn=DriverManager.getConnection(url,name,pwd);//獲取連接對象??????????????return?conn;??????????}catch(ClassNotFoundException?e){??????????????e.printStackTrace();??????????????return?null;??????????}catch(SQLException?e){??????????????e.printStackTrace();??????????????return?null;??????????}??????}????????????public?static?void?closeAll(Connection?conn,PreparedStatement?ps,ResultSet?rs){??????????try{??????????????if(rs!=null){??????????????????rs.close();??????????????}??????????}catch(SQLException?e){??????????????e.printStackTrace();??????????}??????????try{??????????????if(ps!=null){??????????????????ps.close();??????????????}??????????}catch(SQLException?e){??????????????e.printStackTrace();??????????}??????????try{??????????????if(conn!=null){??????????????????conn.close();??????????????}??????????}catch(SQLException?e){??????????????e.printStackTrace();??????????????}??????}????????????public?static?void?main(String[]?args)?throws?SQLException??????{????????????????????Connection?cc=JDBCUtlTool.getConnection();????????????????????if(!cc.isClosed())????????????System.out.println("Succeeded?connecting?to?the?Database!");??????????Statement?statement?=?cc.createStatement();??????????String?sql?=?"select?*?from?test2";??????????ResultSet?rs?=?statement.executeQuery(sql);??????????while(rs.next())?{??????????????System.out.println(rs.getString("id")+"");??????????}??????????}??}??
總結
以上是生活随笔為你收集整理的java 连接mysql 并测试是否成功的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。