用java连接到mysql数据库

用java连接到mysql数据库

 

  1. 下载 mysql-connector-java-3.0.15-ga.zip ,并解压。
  2. 把里面的文件 mysql-connector-java-3.0.15-ga-bin.jar  和 lib 目录底下的所有文件(包括 jdbc2_0-stdext.jar 和 jta-spec1_0_1.jar )拷贝到项目 myweb 中的目录 WebContent/WEB-INF/lib 下面:

  3. 刷新 myweb 项目的 lib 目录:

  4. 建立一个获取与数据库连接的类 MyDBConnection.java :

    添加取得连接的静态函数:

      /**
    * 取得mysql数据库连接
    * @return
    * @throws InstantiationException
    * @throws IllegalAccessException
    * @throws ClassNotFoundException
    * @throws SQLException
    */
    public static Connection getConnection()
                    throws InstantiationException,
                    IllegalAccessException,
                    ClassNotFoundException,
                    SQLException{
        String driver =
    "com.mysql.jdbc.Driver";
        String database =
    "testdb";
        String user =
    "zeng";
        String password =
    "zengrizhang";
        String url =
    "jdbc:mysql://localhost/"+database+"?user="+user+"&password="+password;
     
        Class.forName(driver).newInstance();
     
        Connection conn = DriverManager.getConnection(url);
     
        return conn;
    }

    测试连接是否成功:

    public static void main(String[] args) {
        try{
            getConnection();
            System.out.println(
    "连接成功!");
        }
    catch(Exception e){
            System.out.println(
    "连接失败!");
            e.printStackTrace();
        }
    }
     

    完整的代码: /*
    * 创建日期 2004-10-20
    *
    * 更改所生成文件模板为
    * 窗口 > 首选项 > Java > 代码生成 > 代码和注释
    */
    package myweb;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    /**
    * @author
    Administrator
    *
    *
    更改所生成类型注释的模板为
    * 窗口 > 首选项 > Java > 代码生成 >
    代码和注释
    */
    public class MyDBConnection {
       
    /**
        *
    取得mysql数据库连接
        *
    @return
        * @throws
    InstantiationException
        * @throws
    IllegalAccessException
        * @throws
    ClassNotFoundException
        * @throws
    SQLException
        */
        public static Connection getConnection()
                            throws InstantiationException,
                            IllegalAccessException,
                            ClassNotFoundException,
                            SQLException{
            String driver = "com.mysql.jdbc.Driver";
            String database = "testdb";
            String user = "zeng";
            String password = "zengrizhang";
            String url = "jdbc:mysql://localhost/"+database+"?user="+user+"&password="+password;
         
            Class.forName(driver).newInstance();
     
            Connection conn = DriverManager.getConnection(url);
     
            return conn;
        }
       
    /**
        *
       
    */
        public MyDBConnection() {
            super();
             // TODO
    自动生成构造函数存根
        }
        public static void main(String[] args) {
            try{
                getConnection();
                System.out.println("连接成功!");
            }catch(Exception e){
                System.out.println("连接失败!");
                e.printStackTrace();
            }
        }
    }

  5. 运行,查看结果:

  6. 与 myweb 项目中的 Logon.java 连接。

    在类Logon.java 中的方法 doPost 中,添加保存到数据库的代码:

      //以下代码将用户名和密码保存到数据库
    boolean isSuccess = false;
    String errorMessage =
    "";
    Connection conn =
    null;
    try{
        conn = MyDBConnection.getConnection();
        String sql =
    "insert into myuser(username,password) values(?,?)";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1,username);
        pstmt.setString(2,password);
        pstmt.executeUpdate();
     
    //执行成功
        isSuccess = true;
     }
    catch(Exception e){
        if(conn != null) try {
            conn.rollback();
         }
    catch (SQLException e1) {
     
            e1.printStackTrace();
        }
        e.printStackTrace();
    //执行失败
        isSuccess = false;
        errorMessage = e.getMessage();
    }
    finally{
        if(conn != null) try {
            conn.close();
        }
    catch (SQLException e1) {
     
            e1.printStackTrace();
        }
    }
     
    //输出结果
    if(isSuccess){
        System.out.println(
    "成功添加用户到数据库。");
    }
    else{
        System.out.println(
    "添加用户到数据库失败。错误员应为:" + errorMessage);
    }

     完整的代码package myweb;
    import javax.servlet.Servlet;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    /**
    * @version
    1.0
    *
    @author
    */
    public class LogonServlet extends HttpServlet implements Servlet {
    /**
    * @see javax.servlet.GenericServlet#void
    ()
    */
        public void init() throws ServletException {
            super.init();
        }
        public void doPost(HttpServletRequest request,
                                    HttpServletResponse response)
                                    throws ServletException, IOException {
            request.setCharacterEncoding("GBK");
            String username=request.getParameter("username");
            String password=request.getParameter("password");
            System.out.println("用户名:"+username);
            System.out.println("密码:"+password);
            
    //以下代码将用户名和密码保存到数据库
            boolean isSuccess = false;
            String errorMessage = "";
            Connection conn = null;
            try{
                conn = MyDBConnection.getConnection();
                String sql = "insert into myuser(username,password) values(?,?)";
                PreparedStatement pstmt = conn.prepareStatement(sql);
                pstmt.setString(1,username);
                pstmt.setString(2,password);
                pstmt.executeUpdate();
     
    //执行成功
                isSuccess = true;
            }catch(Exception e){
                if(conn != null) try {
                    conn.rollback();
                } catch (SQLException e1) {
     
                    e1.printStackTrace();
                }
                e.printStackTrace();
    //执行失败
                isSuccess = false;
                errorMessage = e.getMessage();
            }finally{
                if(conn != null) try {
                    conn.close();
                } catch (SQLException e1) {
         
                    e1.printStackTrace();
                }
            }
     
    //输出结果
            if(isSuccess){
                System.out.println("成功添加用户到数据库。");
            }else{
                System.out.println("添加用户到数据库失败。错误员应为:" + errorMessage);
            }
        }
    }
     

  7. 运行 logon.jsp

    出现页面:

    点击 登陆 后,在控制台看到结果:

    在数据库看到的结果:(粉色为添加进去的数据)

    再次运行,并设置用户名为 zeng :

    点击登陆后的结果:

    这是因为表 myuser 中的字段 username 是主键,不能有多条记录具有同一个值。换一个用户名就可以成功保存。

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值