利用jdbc方式连接数据库。
1.添加mysql驱动jar包
我用的是这个驱动包mysql-connector-java-5.1.26-bin.jar
添加方式:
2.加载MySql驱动类
1 private void LoadDriver() { 2 try { 3 String forName = "com.mysql.jdbc.Driver"; 4 // 加载MySql的驱动类 5 Class.forName(forName); 6 System.out.println("MySql驱动加载成功"); 7 } catch (ClassNotFoundException e) { 8 System.out.println("找不到驱动程序类 ,加载驱动失败!"); 9 // e.printStackTrace(); 10 } 11 }
3.连接数据库
1 public void OpenLik() { 2 try { 3 String url = "jdbc\:mysql\://localhost\:3306/test1"; 4 String username = "root"; 5 String password = "root"; 6 System.out.println(url + username + password); 7 con = DriverManager.getConnection(url, username, password); 8 System.out.println("数据库连接成功!"); 9 } catch (SQLException se) { 10 System.out.println("数据库连接失败!"); 11 // se.printStackTrace(); 12 } 13 }
4.创建数据库执行命令,并传入sql 操作语句
1 public Statement GetSqlStringCommand(String query) { 2 // TODO Auto-generated method stub 3 PreparedStatement pstmt = null; 4 try { 5 pstmt = con.prepareStatement(query); 6 System.out.println("获取命令成功"); 7 } catch (Exception ex) { 8 System.out.println("获取命令失败"); 9 // ex.printStackTrace(); 10 } 11 return pstmt; 12 }
5.根据数据库命令,操作sql命令语句
1 public ResultSet ExecuteDataSet(Statement cmd) { 2 // TODO Auto-generated method stub 3 ResultSet RS = null; 4 PreparedStatement cmd_ = (PreparedStatement) cmd; 5 try { 6 RS = cmd_.executeQuery(); 7 System.out.println("获取ResultSet成功"); 8 } catch (Exception ex) { 9 System.out.println("获取ResultSet失败"); 10 // ex.printStackTrace(); 11 } 12 return RS; 13 }
这样就可以进行数据库的连接了!!!
时间: 2024-10-22 06:26:54