JAVA EE 连接MySql数据库

  接上次JDBC 使用Derby数据库连接之后 这次尝试使用MySql 连接=-=

  我们得先下载Mysql的驱动包:mysql-connector-java-5.1.41-bin.jar

  下载之后 导入:

完成这个之后我们打开MySql Workbench 开启本地数据库 并创建 USERINFO 库

然后再到index.jsp中写入:

<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
    <%
   //声明Connection对象
        Connection con;
        //驱动程序名
        String driver = "com.mysql.jdbc.Driver";
        //URL指向要访问的数据库名mydata
        String url = "jdbc:mysql://localhost:3306/USERINFO";
        //MySQL配置时的用户名
        String user = "root";
        //MySQL配置时的密码
        String password = "699307";
        //遍历查询结果集
         Connection conn = null;
        try {
            //加载驱动程序
            Class.forName(driver);
            //1.getConnection()方法,连接MySQL数据库!!
            conn = DriverManager.getConnection(url,user,password);
            if(!conn.isClosed())
                System.out.println("Succeeded connecting to the Database!");
            //2.创建statement类对象,用来执行SQL语句!!
            Statement st = conn.createStatement();
        
        //执行sql语句
         String sql = "select * from USERINFO";
        //增删改查表中的内容,用executeUpdate方法
       st.executeUpdate("insert into USERINFO(USERID, USERNAME) values (1, 'NOSTRING')");
       st.executeUpdate("insert into USERINFO(USERID, USERNAME) values (2, 'BECHAR')");
       st.executeUpdate("insert into USERINFO(USERID, USERNAME) values (3, 'ALEXVIEW')");
       
        //读取表的内容,用executeQuery方法
        ResultSet rs = st.executeQuery("select * from USERINFO");
        //循环输出内容
        while(rs.next()){
            int userID = rs.getInt(1);
            String username = rs.getString(2);
            out.println("-------------------<br>");
            out.println("uerid:"+ userID +"<br>");
            out.println("username:"+ username +"<br>");
            out.println("-------------------<br>");
        }
        
    }catch(SQLException e){
        out.print(e.getErrorCode() + "<br>");
        out.print(e.getCause() + "<br>");
        out.print(e.getMessage() + "<br>");
        if(conn != null )
            conn.close();
    }

 %>
  </body>
</html>

写入之后日常访问:

posted @ 2017-04-16 18:19  KelovpString  阅读(4489)  评论(0编辑  收藏  举报