package pack1;
import java.sql.*;
/**
*
* @author LongDT
*/
public class DemoConnection {
}
class ThaoTacCoSoDuLieu {
Connection con;
public ThaoTacCoSoDuLieu(){
try{
con=ketNoi();
}catch(Exception e){
System.out.println(e);
}
}
public Connection ketNoi() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_demo", "root", "");
//db_demo là tên của database, root là username và password là rỗng
return con;
}
public void showData() throws SQLException {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from category");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getByte(3));
}
}
}
class MySQLCon {
public static void main(String args[]) {
ThaoTacCoSoDuLieu coSoDuLieu = new ThaoTacCoSoDuLieu();
try {
Connection con = coSoDuLieu.ketNoi();
//Show Data:
coSoDuLieu.showData();
//Xóa bản ghi
// stmt.executeUpdate("delete from category where id=3");
// System.out.println("Sau khi xóa bản ghi:");
// rs = stmt.executeQuery("select * from category");
// while (rs.next()) {
// System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getByte(3));
// }
// //Thêm bản ghi:
// stmt.executeUpdate("insert category(categoryName) values('ÂBCD'),('Ê1234')");
// System.out.println("Sau khi chèn bản ghi:");
// rs = stmt.executeQuery("select * from category");
// while (rs.next()) {
// System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getByte(3));
// }
// //Sửa bản ghi:
// stmt.executeUpdate("update category set categoryName='Sửa bản ghi' where id=1");
// System.out.println("Sau khi sửa bản ghi:");
// rs = stmt.executeQuery("select * from category");
// while (rs.next()) {
// System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getByte(3));
// }
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}