JavaJDBC【三、增删改查】
2024-10-06 21:51:18
获取数据库连接后,可进行增删改查操作
语句生成:
Statement s = con.createStatement(sql); //生成语句
PreparedStatement ps = (PreparedStatement) c.prepareStatement(sql); //预准备,可以填充参数
ps.setXXX(n,value); //可以通过set来填充参数值,位置,值参数查询:
s.executeUpdate(); //执行非查询操作,增删改
s.executeQuery(); //执行查询
Demo:
public class JDBCDAO {
public static int addJDBC(JDBCModel m) throws SQLException {
Connection c = DBUtil.GetConnection();
// current_time() mysql内置函数,当前时间
String sql = "insert jdbc (id,name,createtime) "
+ "values(?,?,current_time())";
PreparedStatement ps = (PreparedStatement) c.prepareStatement(sql);
ps.setLong(1, 0);// 主键自增
ps.setString(2, m.name);
int re = 0;
try {
// 此处若使用execute,会返回false,但插入成功
// false代表第一个执行结果的返回值不是resultset
re = ps.executeUpdate();
System.out.println(re);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return re;
}
public static int deleteJDBC(int i) throws SQLException {
Connection c = DBUtil.GetConnection();
String sql = "delete from jdbc where id=?";
PreparedStatement ps = (PreparedStatement) c.prepareStatement(sql);
ps.setLong(1, i);
int re = 0;
try {
// 此处若使用execute,会返回false,但插入成功
// false代表第一个执行结果的返回值不是resultset
re = ps.executeUpdate();
System.out.println(re);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return re;
}
public static int updateJDBC(JDBCModel m) throws SQLException {
Connection c = DBUtil.GetConnection();
String sql = "update jdbc set name=? where id=?";
PreparedStatement ps = (PreparedStatement) c.prepareStatement(sql);
ps.setString(1, m.name);
ps.setLong(2, m.id);
int re = 0;
try {
re = ps.executeUpdate();
System.out.println(re);
} catch (SQLException e) {
e.printStackTrace();
}
return re;
}
public static List<JDBCModel> queryJDBC() throws SQLException {
List<JDBCModel> ml = new ArrayList<JDBCModel>();
Connection c = DBUtil.GetConnection();
String sql = "select * from jdbc ";
PreparedStatement ps = (PreparedStatement) c.prepareStatement(sql);
ResultSet re = null;
try {
re = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
if (re != null) {
while (re.next()) {
JDBCModel m = new JDBCModel();
m.setId(re.getInt("id"));
m.setName(re.getString("name"));
m.setCreatetime(re.getDate("createtime"));
ml.add(m);
}
}
return ml;
}
}
最新文章
- poj1966 求顶点连通度
- BootSrap学习
- PHP 将秒数转换成时分秒
- Linux系统中CPU使用率查询常用的5个命令
- EFW框架源代码版本升级记录说明
- C语言提供的位运算符
- ibatis动态sql配置启动时提示:The content of elements must consist of well-formed character data...
- VC++实现在系统托盘来新消息闪烁,鼠标悬停显示窗口
- java新手笔记34 连接数据库
- FCKeditor 插件开发 示例
- [Immutable,js] Immutable.Record() as data models
- shell的特殊符号的表示
- 在IIS上发布Web(使用VS2005)
- sql server 2012 新知识-序列
- 【转】Robust regression(稳健回归)
- 喜马拉雅音频下载工具 - xmlyfetcher
- Cookie浅析
- Lesson 3-1(语句:条件语句)
- ssh连接报错server responded”algorithm negotiation failed”
- dict的基本使用