1 package jdbc; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.sql.Statement; 8 import org.junit.Test; 9 import com.mysql.jdbc.Driver; 10 11 public class JDBCUtil { 12 13 public void ExecuteQuery() { 14 Connection conn = null; 15 Statement stmt = null; 16 ResultSet rs = null; 17 String url = null; 18 String user = null; 19 String password = null; 20 String sql = null; 21 try { 22 Class.forName("com.mysql.jdbc.Driver"); //加载mysq驱动 23 } catch (ClassNotFoundException e) { 24 System.out.println("驱动加载错误"); 25 e.printStackTrace();//打印出错详细信息 26 } 27 try { 28 url = 29 "jdbc:mysql://WIN-7ERP:3306/msk_dev?user=root&password=Root123&useUnicode=true&&characterEncoding=gb2312&autoReconnect = true";//简单写法:url = "jdbc:myqsl://WIN-7ERP:3306/msk_dev? user=root(用户)&password=Root123(密码)"; 30 user = "root"; 31 password = "Root123"; 32 conn = DriverManager.getConnection(url,user,password); 33 } catch (SQLException e) { 34 System.out.println("数据库链接错误"); 35 e.printStackTrace(); 36 } 37 try { 38 stmt = conn.createStatement(); 39 sql = "select*from wq_customer"; 40 rs = stmt.executeQuery(sql);//执行sql语句 41 while(rs.next()) { 42 System.out.print(rs.getString(1) + " "); 43 System.out.print(rs.getString(2) + " "); 44 System.out.println(rs.getString(3) + " "); 45 } 46 } catch (SQLException e) { 47 System.out.println("数据操作错误"); 48 e.printStackTrace(); 49 } 50 //关闭数据库 51 try { 52 if(rs != null) { 53 rs.close(); 54 rs = null; 55 } 56 if(stmt != null) { 57 stmt.close(); 58 stmt = null; 59 } 60 if(conn != null) { 61 conn.close(); 62 conn = null; 63 } 64 } catch(Exception e) { 65 System.out.println("数据库关闭错误"); 66 e.printStackTrace(); 67 } 68 } 69 }