public classJdbcDom{/**
* 建表
* @throws Exception*/@Testpublic voidjianBiao() throws Exception {//贾:加载JDBC驱动(用反射的方式加载Driver(驱动)类)
Class.forName("com.mysql.jdbc.Driver");//联:连接数据库(通过驱动管理器获取数据库连接("数据库地址","数据库账号","数据库秘密"))
Connection connection = DriverManager.getConnection("jdbc:mysql:///2019_9_9","root","root");//欲:获得语句对象,//上下语句是有关联的,只有获取了数据库连接对象才能拿到语句对象;//获取语句对象,才能将sql语句执行到数据库
Statement cs =connection.createStatement();//执:执行sql语句(cs.执行数据更新(CREATE TABLE 表名 (字段名1 数据类型(数据长度) primary key not null AUTO_INCREMENT,字段名2 数据类型(数据长度),....)))//primary key:设为主键//not null:不为空//AUTO_INCREMENT:自增
cs.executeUpdate("CREATE TABLE tabeName2 (ID int primary key not null AUTO_INCREMENT,name varchar(10),age int)");//事:事务关闭
cs.close();//关闭语句连接
connection.close();//关闭数据库连接
}/**
* 删除指定id的数据
* @throws Exception*/@Testpublic voidremoveValue() throws Exception{//贾
Class.forName("com.mysql.jdbc.Driver");//联
Connection connection = DriverManager.getConnection("jdbc:mysql:///2019_9_9","root","root");//欲
Statement cs =connection.createStatement();//执
cs.executeUpdate("DELETE FROM tabename2 WHERE id=1");
System.out.println("删除完成");//事
cs.close();
connection.close();
}/**
* 添加数据
* @throws Exception*/@Testpublic voidaddValue() throws Exception{//贾
Class.forName("com.mysql.jdbc.Driver");//联
Connection connection = DriverManager.getConnection("jdbc:mysql:///2019_9_9","root","root");//欲
Statement cs =connection.createStatement();//执
cs.executeUpdate("INSERT INTO tabename2 VALUES (null,'我去',20)");//事
cs.close();
connection.close();
}/**
* 根据id修改数据
* @throws Exception*/@Testpublic voidsetValue() throws Exception{//贾
Class.forName("com.mysql.jdbc.Driver");//联
Connection connection = DriverManager.getConnection("jdbc:mysql:///2019_9_9","root","root");//欲
Statement cs =connection.createStatement();//执
cs.executeUpdate("UPDATE tabename2 SET name='C',age=3 WHERE id=3");//事
cs.close();
connection.close();
}/**
* 通过ID查询数据
* @throws Exception
**/@Testpublic voidlookValue() throws Exception {//贾
Class.forName("com.mysql.jdbc.Driver");//联
Connection connection = DriverManager.getConnection("jdbc:mysql:///2019_9_9","root","root");//欲
Statement cs =connection.createStatement();//执
ResultSet e = cs.executeQuery("SELECT * FROM tabeName2 WHERE id=1");//要打印数据;判断e.next()不能少。
if(e.next()){
System.out.println(e.getInt("id")+e.getString("name")+e.getInt("age"));
}else{
System.out.println("没有");
}//事
cs.close();
connection.close();
}
/**
*查询所有数据
*
*/
@Testpublic voidlookAllValue() throws Exception{//贾
Class.forName("com.mysql.jdbc.Driver");//联
Connection connection = DriverManager.getConnection("jdbc:mysql:///2019_9_9","root","root");//欲
Statement cs =connection.createStatement();//执
ResultSet executeQuery = cs.executeQuery("SELECT * FROM tabename2");while(executeQuery.next()) {
System.out.println(executeQuery.getInt("id")+"__"+executeQuery.getString("name")+"__"+executeQuery.getInt("age"));
}//事
cs.close();
connection.close();
}
}