黑马程序员技术交流社区

标题: 使用JDBC-ODBC 方式如何连接MySQL数据库? [打印本页]

作者: wang90ling    时间: 2014-11-3 22:49
标题: 使用JDBC-ODBC 方式如何连接MySQL数据库?
使用JDBC-ODBC 方式如何连接MySQL数据库
作者: feng_0207    时间: 2014-11-3 23:15
  1. public static void main(String[] args) {

  2.                 Connection conn = null;
  3.                 Statement st = null;
  4.                
  5.                 try {
  6.                         // 1.注册驱动
  7.                         String driverName = "com.mysql.jdbc.Driver";

  8.                         Class.forName(driverName);
  9.                         // DriverManager.registerDriver(new Driver());

  10.                         // 2.创建连接
  11.                         String url = "jdbc:mysql://localhost:3306/test";
  12.                         String username = "root";
  13.                         String password = "passw0rd";

  14.                         conn = DriverManager.getConnection(url, username,
  15.                                         password);

  16.                         // 3.获得Statement
  17.                         st = conn.createStatement();

  18.                         // 4.执行SQL
  19.                         String sql = "insert into user (usernane, age) " +
  20.                                         "values ('cc', 22)";

  21.                         //String sql2 = "update user set username='zsdsdf' " +
  22.                         //                "where username='cc'";
  23.                        
  24.                         int n = st.executeUpdate(sql);
  25.                 }

  26.                 catch (Exception e)
  27.                 {
  28.                         e.printStackTrace();
  29.                 }
  30.                 finally
  31.                 {
  32.                        
  33.                         try
  34.                         {
  35.                                 // 6.关闭资源
  36.                                 st.close();
  37.                                 conn.close();
  38.                         }
  39.                         catch (SQLException e)
  40.                         {
  41.                                 e.printStackTrace();
  42.                         }
  43.                        
  44.                 }
  45.         }
复制代码
以前的代码  供你参考。





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2