JDBC:java database connectivity,连接数据库
JDBC规范:
1,DriverManager:用于注册驱动
2,Connection:表示与数据库创建的连接
3,Statement:操作数据库sql语句的对象
4,ResultSet:结果集或一张虚拟表
注意:在写Java连接数据库之前必须先导入jar包

查询
public class Demo01_select {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "lml", "123");
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select * from users");
while(rs.next()){
System.out.println(rs.getObject("id"));
System.out.println(rs.getObject("name"));
System.out.println(rs.getObject("password"));
}
rs.close();
stmt.close();
conn.close();
}
}
更新
public class Demo02_update {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "lml", "123");
Statement stmt=conn.createStatement();
int x=stmt.executeUpdate("update users set id=3,name='cn',password='123' where id=2");
if(x>0){
System.out.println("success");
}
stmt.close();
conn.close();
}
}
删除
public class Demo03_delete {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "lml", "123");
Statement stmt=conn.createStatement();
int x=stmt.executeUpdate("delete from users where id=3");
if(x>0){
System.out.println("success");
}
stmt.close();
conn.close();
}
}
添加
public class Demo04_insert {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "lml", "123");
Statement stmt=conn.createStatement();
int x=stmt.executeUpdate("insert into users values(4,'tom','123456')");
if(x>0){
System.out.println("success");
}
stmt.close();
conn.close();
}
}