1.创建连接,下载MySQL驱动(JDBC接口的实现类,就是一个jar包)
public classDemo01 {public static voidmain(String[] args)throwsClassNotFoundException, SQLException {//1. 注册驱动 告诉虚拟机使用的是哪个数据库软件
Class.forName("com.mysql.jdbc.Driver");//2. 获取连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/newdb3", "root", "root");
System.out.println(conn);//3. 创建SQL执行对象
Statement stat =conn.createStatement();//4. 执行SQL语句
String sql = "create table jdbct1 (id int primary key,name varchar(10))";
stat.execute(sql);
System.out.println("执行完成!");//5. 关闭资源
conn.close();
}
}
public classDemo02 {public static void main(String[] args) throwsClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/newdb3", "root", "root");
Statement stat=conn.createStatement();
String sql= "drop table jdbct1";
stat.execute(sql);
System.out.println("执行完成");
conn.close();
}
}
public classDemo03 {public static void main(String[] args) throwsClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/newdb3", "root", "root");
Statement stat=conn.createStatement();//执行增删改SQL//String sql = "insert into emp(empno,ename) values(100,'Tom')";//String sql = "update emp set ename='Jerry' where empno=100";//String sql = "delete from emp where empno=100";//stat.executeUpdate(sql);//执行查询SQL
String sql = "select ename,sal,job from emp";//查询到的结果装进了rs对象中
ResultSet rs =stat.executeQuery(sql);//遍历结果集对象获取数据