JDBC
Java DataBase Connectivity,Java数据库连接
import java.sql.DriverManager;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class Test { public static void main(String[] args) throws ClassNotFoundException, SQLException { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver");// 加载MySQL驱动 // 获取数据库连接对象 conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/school", "root", "123456"); //查 stmt = conn.createStatement(); rs = stmt.executeQuery("select * from student"); while (rs.next()) { // System.out.println(String.format("编号%d,姓名:%s",rs.getInt("id"),rs.getString("name"))); System.out.println(String.format("编号%d,姓名:%s", rs.getInt(1), rs.getString(2)));// 索引从1开始 } //增 stmt.executeUpdate("insert into student(name) values('雷科巴'),('巴乔'),('梅西')");//返回3 //删 stmt.executeUpdate("delete from student"); //改 stmt.executeUpdate("update student set name='席尔瓦' where id=3"); } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } }}
使用预编译语句PrepareStatement
import java.sql.DriverManager;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.PreparedStatement;public class Test { public static void main(String[] args) throws ClassNotFoundException, SQLException { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver");// 加载MySQL驱动 // 获取数据库连接对象 conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/school", "root", "123456"); stmt=conn.prepareStatement("select name from student where id=?"); stmt.setInt(1, 14);//索引从1开始 rs=stmt.executeQuery(); if(rs.next()){ System.out.println(rs.getString("name")); } } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } }}