Java是一門面向?qū)ο缶幊陶Z言,在它的生態(tài)圈中,MySQL是最常用的關(guān)系型數(shù)據(jù)庫之一。Java與MySQL結(jié)合,成為一門非常強(qiáng)大的應(yīng)用程序開發(fā)工具。MySQL操作類是Java中用于操作MySQL數(shù)據(jù)庫的基礎(chǔ)類之一,Java通過這種方式實(shí)現(xiàn)與MySQL數(shù)據(jù)庫的交互。下面我們來了解一下這個(gè)Java MySQL數(shù)據(jù)庫操作類。
Java MySQL數(shù)據(jù)庫操作類可以通過JDBC驅(qū)動(dòng)的方式實(shí)現(xiàn)與MySQL數(shù)據(jù)庫的連接,JDBC驅(qū)動(dòng)可以通過以下方式獲取:
Class.forName("com.mysql.jdbc.Driver"); 連接MySQL數(shù)據(jù)庫;
Java MySQL數(shù)據(jù)庫操作類常常被用在web應(yīng)用程序開發(fā)中,因?yàn)樗梢酝瓿蓪?shù)據(jù)庫的增刪改查等操作。下面展示一個(gè)Java MySQL數(shù)據(jù)庫操作類中的增刪改查方法:
public class MySQLDemo { private String driver = "com.mysql.jdbc.Driver"; private String url = "jdbc:mysql://localhost:3306/test"; private String username = "root"; private String password = "123456"; private Connection conn; public MySQLDemo() { try { Class.forName(driver); conn = DriverManager.getConnection(url, username, password); } catch (Exception e) { e.printStackTrace(); } } //增加記錄 public void add() { PreparedStatement ps; String sql = "insert into students(id, name, age) values(?,?,?)"; try { ps = conn.prepareStatement(sql); ps.setString(1, "001"); ps.setString(2, "Tom"); ps.setInt(3, 18); ps.executeUpdate(); System.out.println("添加記錄成功"); } catch (SQLException e) { e.printStackTrace(); } } //刪除記錄 public void delete() { PreparedStatement ps; String sql = "delete from students where id = ?"; try { ps = conn.prepareStatement(sql); ps.setString(1, "001"); ps.executeUpdate(); System.out.println("刪除記錄成功"); } catch (SQLException e) { e.printStackTrace(); } } //修改記錄 public void modify() { PreparedStatement ps; String sql = "update students set age = ? where id = ?"; try { ps = conn.prepareStatement(sql); ps.setInt(1, 20); ps.setString(2, "001"); ps.executeUpdate(); System.out.println("修改記錄成功"); } catch (SQLException e) { e.printStackTrace(); } } //查詢記錄 public void query() { PreparedStatement ps; ResultSet rs; String sql = "select * from students"; try { ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { System.out.println("id:" + rs.getString("id") + " name:" + rs.getString("name") + " age:" + rs.getInt("age")); } } catch (SQLException e) { e.printStackTrace(); } } //關(guān)閉連接 public void close() { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) { MySQLDemo mySQLDemo = new MySQLDemo(); mySQLDemo.add(); mySQLDemo.modify(); mySQLDemo.delete(); mySQLDemo.query(); mySQLDemo.close(); } }
通過上述代碼,我們可以看到Java MySQL數(shù)據(jù)庫操作類與MySQL數(shù)據(jù)庫的連接方式以及實(shí)現(xiàn)增刪改查等操作的方式。