3C科技 娛樂遊戲 美食旅遊 時尚美妝 親子育兒 生活休閒 金融理財 健康運動 寰宇綜合

Zi 字媒體

2017-07-25T20:27:27+00:00
加入好友
我們連接在使用Java連接資料庫的時候,不管是Oracle資料庫還是Mysql資料庫,都需要一個對應的jar包,Oracle資料庫需要的是ojdbc15.jar包,而Mysql資料庫需要的是mysql-connector-java-5.1.7-bin.jar包,這兩種在網上都可以很方便的找到。2、Java連接Mysql的代碼如下:private static String url = "jdbc:mysql://localhost:3306/test"; private static String userName = "root";private static String password = "root";public static void main(String args) {MysqlConnectTest mysql= new MysqlConnectTest;Connection con = mysql.getConnection;if(con==null){ System.out.println("與mysql資料庫連接失敗!"); }else{ System.out.println("與mysql資料庫連接成功!"); }}3、MysqlConnectTest 類中getConnection方法如下:public Connection getConnection{Connection con = null;try {Class.forName("com.mysql.jdbc.Driver");con = DriverManager.getConnection(url, userName, password);} catch (ClassNotFoundException e) {e.printStackTrace;} catch (SQLException e) {e.printStackTrace;}return con;}4、Mysql執行查看語句:Statement sts = null;String sql = "select * from user_table ";ResultSet resul = null;try {sts = (Statement) con.createStatement;resul = sts.executeQuery(sql);} catch (SQLException e) {e.printStackTrace;}System.out.println("查詢的結果如下:");while(resul.next){System.out.println("user_id: "+resul.getString("user_id")+",user_name: "+resul.getString("user_name")+",user_sex: "+resul.getString("user_sex"));}5、現在執行插入語句,代碼如下:String sql = "insert into user_table values ('3','thiscode','1','28','13351210773')";int i = 0;try {sts = (Statement) con.createStatement;i = sts.executeUpdate(sql);if(i == -1){System.out.println("插入失敗");}else{System.out.println("插入成功");}} catch (SQLException e) {e.printStackTrace;}步驟閱讀END

本文由yidianzixun提供 原文連結

寫了 5860316篇文章,獲得 23313次喜歡
精彩推薦