📄 jdbc表单操作数据库.txt
字号:
// 定义PreapredStatement对象,用于操作数据库
PreparedStatement pstmt = null ;
由于字符串中有 ' 单引号,所以利用Statement插入的时候会造成数据输入不正确
所以使用子接口PreparedStatement来替换他。
对于查询,等操作,方法是把Statement 替换成 PreparedStatement就可以了。
///////////////a.htm//////////////////////////
<form action="b.jsp" method="post">
姓名:<input type="text" name="title"><br>
密码:<input type="password" name="cont"><br>
年龄:<input type="text" name="isleaf"><br>
<input type="submit" value="增加">
</form>
//////////////通过jdbc详解中的jsp代码来改写如下//////////////////////
////////////////b.jsp//////////////////
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<%!
// 定义数据库驱动程序
String DBDRIVER = "com.mysql.jdbc.Driver" ;
// 定义数据库连接地址
String DBURL = "jdbc:mysql://localhost/bbs?user=root&password=root" ;
// 定义数据库连接对象,属于java.sql包中的接口
Connection conn = null ;
// 定义Statement对象,用于操作数据库
Statement stmt = null ;
// 定义一字符串变量,用于保存SQL语句
// 定义PreapredStatement对象,用于操作数据库
PreparedStatement pstmt = null ;
String sql = null ;
// 查询返回的结果集对象
ResultSet rs = null ;
%>
<%
// 1、加载驱动程序
// 接收表单参数
// 处理乱码
request.setCharacterEncoding("GB2312") ;
String title = request.getParameter("title") ;
String cont = request.getParameter("cont") ;
int isleaf = 0 ;
try
{
isleaf = Integer.parseInt(request.getParameter("isleaf")) ;
}
catch(Exception e)
{}
try
{
Class.forName(DBDRIVER) ;
}
catch(Exception e)
{
// 此处使用out.print是处于演示目的,在实际开发中所有的错误消息,绝对不能够通过out.print打印,否则会存在安全问题
out.println("数据库驱动程序加载失败!!!") ;
}
// 2、连接数据库
try
{
conn = DriverManager.getConnection(DBURL) ;
}
catch(Exception e)
{
out.println("数据库连接失败!!!") ;
}
// 3、操作数据库
try
{ // 通过Connection对象实例化Statement对象
//stmt = conn.createStatement() ;
//为sql变量赋值
/*第一,每次页面刷新增加一个值*/
// sql="INSERT INTO article (title,cont,isleaf) VALUES ('我的mysql','jdbc数据增加',28)" ;
/* 第二 插入语句*/
// sql = "UPDATE article SET title='我的mysql',cont='jdbc数据修改' WHERE isleaf=28" ;
/*第三 按isleaf删除记录*/
//sql = "DELETE FROM article WHERE isleaf=28" ;
/*第四 编写查询的SQL语句*/
//sql = "SELECT id,isleaf,title,cont FROM article" ;
// 通过Statement对象执行此SQL语句,注意只用在更新数据库上
//stmt.executeUpdate(sql) ;
//如果是查询数据库,那么就必须用下面的语句,更新语句要去掉
/*此方法返回ResultSet对象*/
// rs = stmt.executeQuery(sql) ;
////////////////////////////////
// 需要重新组合新的SQL语句
sql = "INSERT INTO article (title,cont,isleaf) VALUES (?,?,?)" ;
pstmt = conn.prepareStatement(sql) ;
// 通过Statement对象执行此SQL语句
// 向变量中设置内容
pstmt.setString(1,title) ;
pstmt.setString(2,cont) ;
pstmt.setInt(3,isleaf) ;
pstmt.executeUpdate() ;
}
catch(Exception e)
{
out.println("操作数据库失败!!!") ;
}
// 4、关闭数据库
try
{
// 关闭操作
pstmt.close() ;
// 关闭连接
conn.close() ;
}
catch(Exception e)
{
out.println("数据库关闭失败!!!") ;
}
%>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -