连接mysql数据库:mydata
1 import java.sql.*; 2 3 public class TestMysqlConnection { 4 5 /** 6 * @param args 7 */ 8 public static void main(String[] args) { 9 Connection con=null; 10 PreparedStatement pSta=null; 11 ResultSet rs=null; 12 con = DBManager.getConnection(); 13 String sql = "select * from dept"; 14 try { 15 pSta = con.prepareStatement(sql); 16 rs = pSta.executeQuery(); 17 while (rs.next()) { 18 int depno = rs.getInt("depno"); 19 String dname = rs.getString("dname"); 20 String loc = rs.getString("loc"); 21 System.out.println(depno + "--" + dname + "--" + loc); 22 } 23 } catch (SQLException e) { 24 // TODO Auto-generated catch block 25 e.printStackTrace(); 26 }finally{ 27 DBManager.closeResultSet(rs); 28 DBManager.closeStatement(pSta); 29 DBManager.closeConnection(con); 30 } 31 } 32 } 33 34 class DBManager { 35 public static Connection getConnection() { 36 Connection con = null; 37 38 try { 39 Class.forName("com.mysql.jdbc.Driver"); 40 con = DriverManager 41 .getConnection("jdbc:mysql://localhost:3306/mydata?user=root&password=root"); 42 } catch (ClassNotFoundException e) { 43 // TODO Auto-generated catch block 44 e.printStackTrace(); 45 } catch (SQLException e) { 46 // TODO Auto-generated catch block 47 e.printStackTrace(); 48 } 49 return con; 50 } 51 52 public static void closeResultSet(ResultSet rs) { 53 try { 54 if (rs != null) { 55 rs.close(); 56 rs = null; 57 } 58 } catch (SQLException e) { 59 // TODO Auto-generated catch block 60 e.printStackTrace(); 61 } 62 } 63 64 public static void closeStatement(PreparedStatement pSta) { 65 try { 66 if (pSta != null) { 67 pSta.close(); 68 pSta = null; 69 } 70 } catch (SQLException e) { 71 // TODO Auto-generated catch block 72 e.printStackTrace(); 73 } 74 } 75 76 public static void closeConnection(Connection con) { 77 try { 78 if (con != null && !con.isClosed()) { 79 con.close(); 80 } 81 } catch (SQLException e) { 82 // TODO Auto-generated catch block 83 e.printStackTrace(); 84 } 85 } 86 87 }
PreparedStatement接口继承自Statement接口,PreparedStatement实例包含已编译的SQL语句,且SQL语句可以有输入参数。这些输入参数在SQL语句创建时并未被指定,而是为每个输入参
数保留一个问号作为占位符。在执行PreparedStatement对象之前,必须通过setXXX方法来设置每个输入参数的值。例如:
pSta.setInt(1,1);就是为第一个参数设置整型值1.
pSta.setString(2,"博客园");就是为第二个参数设置String类型值"博客园".