thieumao

Insert - MySQL - Java

Oct 31st, 2013
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package testmysql;
  6.  
  7. import com.mysql.jdbc.Connection;
  8. import java.sql.DriverManager;
  9. import java.sql.SQLException;
  10. import java.sql.Statement;
  11.  
  12. /**
  13.  *
  14.  * @author leo
  15.  */
  16. public class TestMySQL {
  17.  
  18.     private Connection conn;
  19.  
  20.     public void testConnectMySQL() {
  21.         String db = "TestMySQL"; //Tên database
  22.         String user = "root"; //Mặc định là root
  23.         String pass = "admin"; //Mật khẩu quản trị MySQL
  24.         try {
  25.             String url = "jdbc:mysql://localhost/" + db + "?user=" + user + "&password=" + pass;
  26.             Class.forName("com.mysql.jdbc.Driver");
  27.             conn = (Connection) DriverManager.getConnection(url);
  28.             System.out.println("Kết nối thành công.");
  29.         } catch (Exception e) {
  30.             System.out.println("Lỗi: " + e.getMessage());
  31.         }
  32.  
  33.         try {
  34.             Statement stmt = conn.createStatement();
  35.             String sql = "insert into user(username,password,level) values ('thieumao','123456','1')";
  36.             stmt.executeUpdate(sql);
  37.             stmt.close();
  38.         } catch (SQLException e) {
  39.             e.printStackTrace();
  40.         }
  41.     }
  42.  
  43.     public static void main(String[] args) {
  44.         TestMySQL tm = new TestMySQL();
  45.         tm.testConnectMySQL();
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment