加入收藏 | 设为首页 | 会员中心 | 我要投稿 武汉站长网 (https://www.027zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

HttpServlet 实现 MySQL 数据库的插入操作

发布时间:2022-12-08 13:39:38 所属栏目:MySql教程 来源:未知
导读: 实现步骤1. 准备数据库的地址、用户名和密码
public static final String url = "jdbc:mysql://localhost:3306/budaye_test01";
public static final String name = "root";
public static

实现步骤1. 准备数据库的地址、用户名和密码

public static final String url = "jdbc:mysql://localhost:3306/budaye_test01";
public static final String name = "root";
public static final String pass = "123456";

复制

Jetbrains全家桶1年46数据库插入操作,售后保障稳定

2. 加载数据库

Class.forName("com.mysql.cj.jdbc.Driver");

复制

这里注意,com.mysql.jdbc.Driver 已弃用。

3. 连接数据库

Connection conn = null;
conn = DriverManager.getConnection(url, name, pass);

复制

4. 插入数据库

// 读请求参数
String parName = request.getParameter("name");
String age = request.getParameter("age");
PreparedStatement prep = null;
prep = conn.prepareStatement("insert into " + "name_table(name,age) " + "values(?,?)");
prep.setString(1, parName);
prep.setDouble(2, Integer.parseInt(age));
prep.executeUpdate();

复制

完整代码

public class UpdateNowList extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String url = "jdbc:mysql://localhost:3306/budaye_test01";
	public static final String name = "root";
	public static final String pass = "mima";

mysql存储过程批量插入数据_数据库插入操作_sql 触发器update 插入数据

Connection conn = null; /** * @see HttpServlet#HttpServlet() */ public UpdateNowList() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // 读请求参数 String parName = request.getParameter("name"); String age = request.getParameter("age"); PreparedStatement prep = null; try { // Class.forName("com.mysql.jdbc.Driver"); //已被弃用 Class.forName("com.mysql.cj.jdbc.Driver"); System.out.println("Success loading Mysql Driver!"); conn = DriverManager.getConnection(url, name, pass); System.out.println("Success connect Mysql server!");

mysql存储过程批量插入数据_sql 触发器update 插入数据_数据库插入操作

prep = conn.prepareStatement("insert into " + "name_table(name,age) " + "values(?,?)"); prep.setString(1, parName); prep.setDouble(2, Integer.parseInt(age)); prep.executeUpdate(); out.println("插入成功"); } catch (Exception e) { // 记日志 e.printStackTrace(); out.println("连接数据库失败,稍后重试"); } finally { if (prep != null) { try { prep.close(); } catch (SQLException e) { } } if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } } }

复制

PS:更多更多内容……,请查看 –> 《Server 开发》 PS:更多更多内容……,请查看 –> 《Server 开发》 PS:更多更多内容……,请查看 –> 《Server 开发》

(编辑:武汉站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!