JSP连接MySQL数据库
本Markdown编辑器使用[StackEdit][6]修改而来,用它写博客,将会带来全新的体验哦:
工具:Eclipse Jee、MySQL
JDBC驱动(https://dev.mysql.com/downloads/file/?id=470333)-
1.在项目资源管理器中,右击web项目–>属性–>Java构建路径–>单击Classpath变量–>添加外部变量JAR(X)…–>选择下载好的jdbc包
2..jsp加载头文件如下
<%@ page import=”com.mysql.jdbc.Driver” %><%–加载连接数据库必备的jdbc驱动–>
<%@ page import=”java.sql.*” %><%–连接数据库 –%>
3.body部分↓
<body>
<%
//————连接数据库的基本操作 ————
String driverName="com.mysql.jdbc.Driver";//驱动程序名
Class.forName("com.mysql.jdbc.Driver");//加载驱动
String userName="root";//数据库用户名
String userPasswd="123456";//密码
String dbName="db_name#";//数据库名
String tableName="user";//要jsp要使用的表名
//↓联结字符串
String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+userPasswd+"&useUnicode=true&characterEncoding=utf-8";
Connection connection=DriverManager.getConnection(url);//连接数据库
<%--以上代码是连接数据库的核心代码,以下代码是登录项目所需,供参考--%>
Statement statement = connection.createStatement();
//out.println(user);//调试
if(connection != null){
String sql = "select * from users where user_name='"+user+"' and user_pwd='"+ password + "'";
ResultSet rs = statement.executeQuery(sql);
if(rs.next()){
out.println("<script language='javascript'>alert('用户存在 登录成功!');window.location.href='http://localhost:8080/secondary_market_web/Primary/index.html';</script>");
//response.sendRedirect("Home.jsp");
}else{
out.println("<script language='javascript'>alert('登录失败! 请重新登录!');window.location.href='Login.jsp';</script>");
// response.sendRedirect("Login.jsp");//密码不对返回到登陆
}
}
//statement.close();
//connection.close();
%>
</body>