| 实现步骤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";
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!");
 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 开发》 (编辑:鹰潭站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |