JSP连接MySQL数据库

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值