[JavaEE] JDBC Basic Technology

In this section, I wrote a complete example [I am the download link (●'◡'●)]
. You need to create a simple database according to the content required in the code.
Change database password and database name and you can use it. There are problems. contact me~

  1. Fundamental
    write picture description here

  2. MySql driver problem:
    (1) Add the driver to the current Web project:
    (2) Right-click the current Web project;
    select Build path → add External Archives → add mysql-connector-java-5.1.34-bin.jar.
    (3) Then copy the driver to the WEB-INF/lib of the current project (key).
    (4) Finally, deploy the driver to the Tomcat container WEB-INF/lib (see later, not
    required ).
    mysql-connector-java-5.1.34-bin.jar [I am the download link (●'◡'●)]
    JDBC query:

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ page import="java.sql.*"%>
<%
String url ="jdbc:mysql://localhost:3306/testdb"; //数据库连接串,Mysql默认端口号3306
Class.forName("org.gjt.mm.mysql.Driver").newInstance(); //加载驱动程序
Connection conn= DriverManager.getConnection(url,"root","dba"); //建立连接
String sql="select * from users";
PreparedStatement pStmt = conn.prepareStatement(sql);
ResultSet rs=pStmt.executeQuery( );//executeQuery()用于执行select语句
while( rs.next() ){ //循环遍历结果集
out.print( rs.getString("id")+" " );
out.print( rs.getString("username")+" " );
out.print( rs.getString("password")+" <br/>" );
}
//关闭
rs.close(); pStmt.close(); conn.close(); %>

JDBC conditional query:

<%
String url ="jdbc:mysql://localhost:3306/testdb"; //数据库连接字符串
Class.forName("org.gjt.mm.mysql.Driver").newInstance(); //加载驱动程序
Connection conn= DriverManager.getConnection(url,"root","dba"); //建立连接
String sql="select * from users where username=? and password=?";
PreparedStatement pStmt = conn.prepareStatement(sql);
String username=request.getParameter("username");
String password=request.getParameter("password");
pStmt.setString(1,username);
pStmt.setString(2,password);
ResultSet rs=pStmt.executeQuery( );
if( rs.next() ){
out.print("你已登录,欢迎"+username);
}
else{
out.print("用户名或密码错");
}
//关闭
rs.close(); pStmt.close(); conn.close(); %>

JDBC add:

<%
String url ="jdbc:mysql://localhost:3306/testdb"; //数据库连接字符串
Class.forName("org.gjt.mm.mysql.Driver").newInstance(); //加载驱动程序
Connection conn= DriverManager.getConnection(url,"root","dba"); //建立连接
String sql="insert into users values(null,?,?)";
PreparedStatement pStmt = conn.prepareStatement(sql);
//此处省略用户名检测
String username=request.getParameter("username");
String password=request.getParameter("password");
pStmt.setString(1,username);
pStmt.setString(2,password);
int cnt=pStmt.executeUpdate();
if(cnt>0){
out.print("注册成功");
}
else{
out.print("用户已存在, <a href='register.jsp'>重新注册</a>");
}
//关闭
pStmt.close(); conn.close(); %>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325731303&siteId=291194637