jdbc 查询 操作
1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.ResultSet; 4 import java.sql.SQLException; 5 import java.sql.Statement; 6 7 public class Marin { 8 9 public static void main(String[] args) { 10 ResultSet rs = null; 11 Statement stmt = null; 12 Connection connection =null; 13 try { 14 Class.forName("com.mysql.jdbc.Driver"); 15 String url = "jdbc:mysql://127.0.0.1:3306/school2?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC"; 16 17 connection= DriverManager.getConnection(url, "root","123456" ); 18 19 String sql ="select subjectName, emial FROM subject2"; 20 21 stmt =connection.createStatement(); 22 rs=stmt.executeQuery(sql); 23 24 while(rs.next()) { 25 String a=rs.getString(1); 26 int b = rs.getInt(2); 27 System.out.println(a+"\t"+b); 28 } 29 } catch (ClassNotFoundException e) { 30 31 }catch (SQLException e) { 32 33 }finally { 34 try { 35 rs.close(); 36 stmt.close(); 37 connection.close(); 38 } catch (SQLException e) { 39 40 e.printStackTrace(); 41 } 42 } 43 } 44 }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Marin2 { public void getTitle(String subjectName,int emial) { Connection con =null; PreparedStatement ps =null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://127.0.0.1:3306/school2?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8"; con =DriverManager.getConnection(url, "root", "123456"); String sql ="select subjectName, emial FROM subject2 where subjectName=? or emial=?"; ps = con.prepareStatement(sql); ps.setString(1, subjectName); ps.setInt(2, emial); rs = ps.executeQuery(); while(rs.next()) { String a=rs.getString("subjectName"); int b = rs.getInt("emial"); System.out.println(a+"\t"+b); } } catch (ClassNotFoundException e) { e.printStackTrace(); }catch (SQLException e) { e.printStackTrace(); }finally { try { rs.close(); ps.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void main(String[] args) { Marin2 m =new Marin2(); m.getTitle("老王",242424 ); } }