thieumao

Kết nối với MySQL với Java đơn giản

Oct 27th, 2013
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.89 KB | None | 0 0
  1. package testmysql;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5.  
  6. /**
  7.  *
  8.  * @author Thieu Mao
  9.  */
  10. public class TestMySQL {
  11.  
  12.     private Connection conn;
  13.  
  14.     public void testConnectMySQL() {
  15.         String db = "TestMySQL"; //Tên database
  16.         String user = "root"; //Mặc định là root
  17.         String pass = "admin"; //Mật khẩu quản trị MySQL
  18.         try {
  19.             String url = "jdbc:mysql://localhost/" + db + "?user=" + user + "&password=" + pass;
  20.             Class.forName("com.mysql.jdbc.Driver");
  21.             conn = DriverManager.getConnection(url);
  22.             System.out.println("Kết nối thành công.");
  23.         } catch (Exception e) {
  24.             System.out.println("Lỗi: " + e.getMessage());
  25.         }
  26.     }
  27.  
  28.     public static void main(String[] args) {
  29.         TestMySQL tm = new TestMySQL();
  30.         tm.testConnectMySQL();
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment