jsp向mysql数据库中添加数据

一共有两种方法

这是第一种


<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="java.sql.*"%>
<html>
<body>
 <%
 String dbname = "studentsystem";
 String dbuser = "root";
 String dosql = "select * from user";
 String dbpasswd = "";

if(dbpasswd == "null")
 dbname = "";

String username = request.getParameter("username");
 String userid = request.getParameter("userid");
 String usersex = request.getParameter("usersex");

if (username == null)
 username = "";
 if (userid == null)
 userid = "";
 if (usersex == null)
 usersex = "";
 try {

/** 链接数据库参数 **/
 String driverName = "com.mysql.jdbc.Driver"; //驱动名称
 String DBUser = "root"; //mysql用户名
 String DBPasswd = ""; //mysql密码
 String DBName = "studentsystem"; //数据库名

//数据库完整链接地址
 String connUrl = "jdbc:mysql://localhost/" + DBName + "?user="
 + DBUser + "&password=" + DBPasswd;

//加载数据库驱动
 Class.forName(driverName).newInstance();

//链接数据库并保存到 conn 变量中
 Connection con = DriverManager.getConnection(connUrl);
 out.println("数据库连接成功!");
 String sql = "insert into user(userid,username,usersex) values('"
 + userid + "','" + username + "','" + usersex + "')";


 out.println(sql);
 PreparedStatement stmt = con.prepareStatement(sql);

try {
 stmt.executeUpdate();
 } catch (Exception e) {
 e.printStackTrace();
 }

con.close();
 } catch (Exception e) {
 e.printStackTrace();
 }
 %>

</body>
</html>

 

 

第二种方法


<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="java.sql.*"%>
<html>
<body>
 <%
 String dbname = "studentsystem";
 String dbuser = "root";
 String dosql = "select * from user";
 String dbpasswd = "";

if(dbpasswd == "null")
 dbname = "";

String username = request.getParameter("username");
 String userid = request.getParameter("userid");
 String usersex = request.getParameter("usersex");

if (username == null)
 username = "";
 if (userid == null)
 userid = "";
 if (usersex == null)
 usersex = "";
 try {

/** 链接数据库参数 **/
 String driverName = "com.mysql.jdbc.Driver"; //驱动名称
 String DBUser = "root"; //mysql用户名
 String DBPasswd = ""; //mysql密码
 String DBName = "studentsystem"; //数据库名

//数据库完整链接地址
 String connUrl = "jdbc:mysql://localhost/" + DBName + "?user="
 + DBUser + "&password=" + DBPasswd;

//加载数据库驱动
 Class.forName(driverName).newInstance();

//链接数据库并保存到 conn 变量中
 Connection con = DriverManager.getConnection(connUrl);
 out.println("数据库连接成功!");

PreparedStatement stm = con.prepareStatement("insert into user(userid,username,usersex) values(?,?,?)");
 stm.setString(1,userid);
 stm.setString(2,username);
 stm.setString(3,usersex);
 try
 {
 stm.executeUpdate();
 }
 catch(Exception e)
 {
 e.printStackTrace();
 }

 con.close();
 }
 catch (Exception e)
 {
 e.printStackTrace();
 }
 %>
</body>
</html>

发表评论

电子邮件地址不会被公开。 必填项已用*标注