300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > java 数据库改操作_数据库的插入 修改 删除操作(java实现)

java 数据库改操作_数据库的插入 修改 删除操作(java实现)

时间:2020-06-19 02:42:42

相关推荐

java 数据库改操作_数据库的插入 修改 删除操作(java实现)

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class JDBCTest {

// 定义数据库访问参数

String url = "jdbc:sqlserver://localhost:1433; DatabaseName=lihongchao";

String user = "sa";

String password = "a123456";

static String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

Connection conn;

Statement st;

// 1、加载驱动

static {

try {

Class.forName(driverName);

} catch (ClassNotFoundException e) {

System.out.println("驱动加载失败");

}

}

// 2、创建连接对象

public Connection getConnection() throws SQLException{

conn=DriverManager.getConnection(url,user,password);

return conn;

}

public void add() throws ClassNotFoundException, SQLException {

// 定义sql语句

String sql1="insert into Table2(id,name,grade) values('1114','大学英语',3)";

String sql2="insert into Table2(id,name,grade) values('1115','体育',2)";

String sql3="insert into Table2(id,name,grade) values('1116','马克思',3)";

// 3、创建语句对象

st =getConnection().createStatement();

// st.executeUpdate(sql1);

st.executeUpdate(sql2);

st.executeUpdate(sql3);

// 4、遍历结果集:此处插入记录不需要

// 5、关闭资源对象

st.close();

getConnection().close();

}

public void update() throws ClassNotFoundException, SQLException {

// 定义sql语句

String sql1="update Table2 set grade=1 where grade=2";

// 3、创建语句对象

st =getConnection().createStatement();

st.executeUpdate(sql1);

// 4、遍历结果集:此处插入记录不需要

// 5、关闭资源对象

st.close();

getConnection().close();

}

public void delete() throws ClassNotFoundException, SQLException {

// 定义sql语句

String sql1="delete Table2 where id='1115'";

String sql2="delete Table2 where id='1116'";

// 3、创建语句对象

st =getConnection().createStatement();

st.executeUpdate(sql1);

st.executeUpdate(sql2);

// 4、遍历结果集:此处插入记录不需要

// 5、关闭资源对象

st.close();

getConnection().close();

}

public static void main(String[] args) throws ClassNotFoundException,SQLException {

JDBCTest jt=new JDBCTest();

jt.add();

jt.update();

jt.delete();

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。