未分类
2020-10-14 13:23:51
1822677238@qq.com
手机扫码查看
2020Javaweb教程之JDBC总结
statement执行DDL
public class TestJDBC {
public static void main(String[] args) {
Connection connection=null;
Statement statement=null;
try{
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.创建Connection对象
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demos", "root", "root");
//3.创建执行SQL语句的对象
statement = connection.createStatement();
//4.sql语句
boolean execute = statement.execute("create table stu(id int auto_increment primary key,sname varchar(20),sex varchar(2))");
System.out.println(execute);
}catch (Exception e){}finally {
try{
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}catch (Exception e){}
}
}
}
statement执行DML
public class TestJDBC {
public static void main(String[] args) {
Connection connection=null;
Statement statement=null;
try{
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.创建Connection对象
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demos", "root", "root");
//3.创建执行SQL语句的对象
statement = connection.createStatement();
//4.sql语句
//新增数据
//int i = statement.executeUpdate("insert into gamer(gname)values ('admin')");
//修改数据
//int i = statement.executeUpdate("update gamer set gname='admin888' where id=2");
//删除数据
int i = statement.executeUpdate("delete from gamer where id=2");
if (i > 0) {
System.out.println("OK");
}else{ System.out.println("ERR");}
}catch (Exception e){}finally {
try{
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}catch (Exception e){}
}
}
}
statement执行DQL
public class TestJDBC {
public static void main(String[] args) {
Connection connection=null;
Statement statement=null;
ResultSet resultSet=null;
try{
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.创建Connection对象
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demos", "root", "root");
//3.创建执行SQL语句的对象
statement = connection.createStatement();
//4.sql语句
String sql="select id,sname,sex from stu";
//5.执行SQL语句
resultSet = statement.executeQuery(sql);
//6.遍历
while (resultSet.next()) {
int id = resultSet.getInt(1);
String sname = resultSet.getString("sname");
String sex = resultSet.getString("sex");
System.out.println(id+":"+sname+":"+sex);
}
}catch (Exception e){}finally {
try{
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}catch (Exception e){}
}
}
}
- 本页地址 https://www.9713job.com/?p=2366
- 上一篇 <<2020Javaweb教程之JDBC实现用户登录
- 下一篇 >>2020Javaweb教程之JDBC应用



发表回复