Eclipse(Java EE)连接Mysql数据库

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

  下载之后 导入:

Eclipse(Java EE)连接Mysql数据库_第1张图片

Eclipse(Java EE)连接Mysql数据库_第2张图片

完成这个之后我们打开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+"/";
%>



  
    
    
    My JSP 'index.jsp' starting page
    
    
        
    
    
    
  
  
  
    <%
   //声明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("-------------------
"); out.println("uerid:"+ userID +"
"); out.println("username:"+ username +"
"); out.println("-------------------
"); } }catch(SQLException e){ out.print(e.getErrorCode() + "
"); out.print(e.getCause() + "
"); out.print(e.getMessage() + "
"); if(conn != null ) conn.close(); } %>

写入之后日常访问:

Eclipse(Java EE)连接Mysql数据库_第3张图片


感谢,原博文:http://www.cnblogs.com/Stringair/p/6719458.html


你可能感兴趣的:(Eclipse(Java EE)连接Mysql数据库)