Java中使用JDBC連接數據庫
-
加載驅動(告訴Java程序,即將要鏈接的是哪中類型的數據庫)
-
獲取鏈接【創建數據庫連接】(表示JVM的進程和數據庫進程之間的通道打開了,數據進程之間通信,重量級的,使用完成之后一定要關閉進程)
-
獲取數據庫操作對象【創建執行sql的對象】
-
執行語句【DQL,DML...】
-
處理執行結果【數據結果集】(只用在執行查詢SELECT語句時,才會處理查詢結果集)
-
釋放資源(使用完資源后一i定要關閉資源)
pox.xml文件配置(下載驅動)
1 <dependencies> 2 <dependency> 3 <groupId>mysql</groupId> 4 <artifactId>mysql-connector-java</artifactId> 5 <version>5.1.46</version> 6 </dependency> 7 </dependencies>
代碼示例一:
直接注冊驅動操作數據庫
此方法操作鏈接數據庫不推薦使用,操作不方便,更不好維護,數據庫之間切換繁瑣
import java.sql.*; public class ChengDatebaseInsert { public static void main(String[] arge) { Connection coon = null; PreparedStatement statement = null; try { //注冊驅動 Class.forName("com.mysql.jdbc.Driver"); //獲取數據庫連接(里面依次是jdbc:mysql://主機號:端口號/數據庫名),用戶名,用戶密碼 try { coon = DriverManager.getConnection("jdbc:mysql://localhost:3306/center?serverTimezone=UTC&userSSL=false" , "root", "123456"); System.out.println(coon + "獲取成功!"); //需要執行的sql語句 String sql = "insert INTO center_user(CENTER_NAME,CENTER_AGE,CENTER_SEX) VALUES(?,?,?) "; //獲取預處理對象 statement = coon.prepareCall(sql); statement.setString(1, "王老虎"); statement.setInt(2, 12); statement.setString(3, "男"); //執行sql(執行幾行,返回幾條記錄) int updatecont = statement.executeUpdate(); System.out.println("更新數據總數據是:" + updatecont); } catch (SQLException throwables) { throwables.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { //關閉jdbc連接 if (statement != null) { try { statement.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (coon != null) { try { coon.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } } }
第二種(新手推薦,實際框架中我們不建議這么定義):
package com.guisha.JDBC; import java.sql.*; public class JDBCTest { public static void main(String[] agre) throws SQLException { PreparedStatement stam = null; Connection conn = null; try { //注冊驅動(常用,不需要接受返回值,我們只需要這個類加載動作) Class.forName("com.mysql.jdbc.Driver"); //獲取鏈接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "guisha"); //許喲啊執行的sql語句 String sql = "update center_user set user_name='王老頭' where user_age='21' "; //創建數據庫操作對象 stam = conn.prepareStatement(sql); // executeUpdate 執行數據SQL更新 //count 返回執行的條數 int count = stam.executeUpdate(); System.out.println(count == 1 ? "修改成功!" : "修改失敗!"); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { //關閉資源 if (stam != null) { stam.close(); } if (conn != null) { conn.close(); } } } }
先了解下簡單的DELETE和UPDATE操作
JDBC操作Delete:
package com.guisha.JDBC; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class JdbcDeleteTest { public static void main(String[] args) { //將數據庫配置定義為變量(開發中我們定義到properties配置文件中去) String Driver = "jdbc:mysql://localhost:3306/user"; String name = "root"; String password = "guisha"; Connection coon = null; Statement strm = null; try { //注冊驅動 Class.forName("com.mysql.jdbc.Driver"); //獲取鏈接 try { coon = DriverManager.getConnection(Driver, name, password); //創建數據庫對象操作對象 strm = coon.createStatement(); //創建需要執行的sql語句 String sql = "delete from center_user where USER_NAME='王琳'"; //執行更新操作 int count = strm.executeUpdate(sql); System.out.println(count == 1 ? "刪除成功!" : "刪除失敗!"); } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (strm != null) { try { strm.close(); } catch (SQLException e) { e.printStackTrace(); } } if (coon != null) { try { coon.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
JDBC操作Update:
package com.guisha.JDBC; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class JdbcDeleteTest { public static void main(String[] args) { //將數據庫配置定義為變量(開發中我們定義到properties配置文件中去) String Driver = "jdbc:mysql://localhost:3306/user"; String name = "root"; String password = "guisha"; Connection coon = null; Statement strm = null; try { //注冊驅動 Class.forName("com.mysql.jdbc.Driver"); //獲取鏈接 try { coon = DriverManager.getConnection(Driver, name, password); //創建數據庫對象操作對象 strm = coon.createStatement(); //創建需要執行的sql語句 String sql = "Update center_user set USER_AGE='19' where USER_NAME='王老頭'"; //執行更新操作 int count = strm.executeUpdate(sql); System.out.println(count == 1 ? "更新成功!" : "更新失敗!"); } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (strm != null) { try { strm.close(); } catch (SQLException e) { e.printStackTrace(); } } if (coon != null) { try { coon.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
代碼示例二:
新建數據庫配置文件,獲取配置文件信息后注冊數據庫驅動
利用反射獲取新建的數據庫配置文件db.properties里的配置信息
示例一:
1 driver=com.mysql.jdbc.Driver 2 url=jdbc:mysql://localhost:3306/user 3 user=root 4 password=guisha
package com.guisha.JDBC; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.ResourceBundle; /** * 方法描述 * 注意:實際開發中不建議把數據庫鏈接數據庫的信息寫死到程序中 * @since: 1.0.0 * @author: Mr.cheng */ public class Properties { public static void main(String[] args) { //使用資源綁定器綁定屬性配置文件 ResourceBundle bundle = ResourceBundle.getBundle("db"); String driver = bundle.getString("driver"); String url = bundle.getString("url"); String user = bundle.getString("user"); String password = bundle.getString("password"); Connection coon = null; Statement strm = null; try { //注冊驅動 Class.forName(driver); //獲取鏈接 try { coon = DriverManager.getConnection(url, user, password); //創建數據庫對象操作對象 strm = coon.createStatement(); //創建需要執行的sql語句 String sql = "Update center_user set USER_AGE='18' where USER_NAME='王老頭'"; //執行更新操作 int count = strm.executeUpdate(sql); System.out.println(count == 1 ? "更新成功!" : "更新失敗!"); } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (strm != null) { try { strm.close(); } catch (SQLException e) { e.printStackTrace(); } } if (coon != null) { try { coon.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
示例二:
driver=com.mysql.jdbc.Driver mysql_url=jdbc:mysql://localhost:3306/center mysql_user=root mysql_password=123456
import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class ChengJdbcTest { private static String driver; private static String mysql_url; private static String mysql_user; private static String mysql_password; static { //新建屬性對象 Properties property = new Properties(); //通過反射,新建字符輸入流,讀取mysql.properties文件 InputStream input = ChengJdbcTest.class.getClassLoader().getResourceAsStream("db.properties"); //將輸入流中讀取到的屬性,加載到properties屬性及對象中 try { //將input 加載到property對象中 property.load(input); //根據鍵,獲取properties中對應的值賦值 driver = property.getProperty("driver"); mysql_url = property.getProperty("mysql_url"); mysql_user = property.getProperty("mysql_user"); mysql_password = property.getProperty("mysql_password"); } catch (IOException e) { e.printStackTrace(); } } //返回數據庫連接 public static Connection getConnection(){ try { //加載驅動 Class.forName(driver); try { //連接數據庫 Connection connection = DriverManager.getConnection(mysql_url, mysql_user, mysql_password); //返回值 return connection; } catch (SQLException throwables) { throwables.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class TestMysql { public static void main(String[] args) throws SQLException { //獲取數據庫連接 Connection connection = ChengJdbcTest.getConnection(); //SQL語句 String sql = "insert INTO center_user(CENTER_NAME,CENTER_AGE,CENTER_SEX) VALUES(?,?,?) "; //執行SQL PreparedStatement statement = connection.prepareCall(sql); //數據庫傳值 statement.setString(1, "小程"); statement.setInt(2, 12); statement.setString(3, "男"); //更新返回的條數,返回Integer int update = statement.executeUpdate(); System.out.println("更新完成:" + update); //關閉資源 if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } }