数据库连接测试:
checkLink.jsp:
<%@page import="java.sql.*" %>
<body>
<%
String url="jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf8";//数据库主机地址以及数据库名
String user="root";//MySQ帐号
String password="123456";//MYSQL密码
try{
Driver driver=new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
}catch (SQLException e){
e.printStackTrace();
out.print("驱动加载失败");
}
try{
Connection connection=DriverManager.getConnection(url,user,password);
out.print("数据库连接成功!");
connection.close();
}catch (Exception e){
out.println("数据库连接失败!");
}
%>
</body>
添加用户:
addUser.jsp:
<%@page import="java.sql.*" %>
<body>
<%
String url="jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf8";//数据库主机地址以及数据库名
String user="root";//MySQ帐号
String password="123456";//MYSQL密码
try{
Driver driver=new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
Connection connection=DriverManager.getConnection(url,user,password);
String sql="insert into user values(?,?,?,?,?,?,?)";
PreparedStatement ps=connection.prepareStatement(sql);
//添加第一条记录
ps.setInt(1,1);
ps.setString(2,"三");
ps.setString(3,"123456");
ps.setInt(4,20);
ps.setString(5,"男");
ps.setString(6,"辽宁");
ps.setString(7,"工人");
ps.executeUpdate();
}catch(Exception e){
out.println("插入数据失败!");
}
%>
</body>
deleteUser.jsp:
<%@page import="java.sql.*" %>
<body>
<%
String url="jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf8";//数据库主机地址以及数据库名
String user="root";//MySQ帐号
String password="123456";//MYSQL密码
try{
Driver driver=new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
Connection connection=DriverManager.getConnection(url,user,password);
String sql="delete from user where name='三'";
PreparedStatement ps=connection.prepareStatement(sql);
ps.executeUpdate();
}catch(Exception e){
out.print("删除记录失败!");
}
%>
</body>