数据库连接测试

最近开发的Javaweb项目老是出错,开始怀疑是不是数据库没有连接正确.


我测试用的数据库如下:



测试代码如下:

package com.IPN.Util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBconTest {
  public static Connection getConnection(){
//备注部分请改为自己的数据库内容.
    String driver="com.mysql.jdbc.Driver";          //获取mysql数据库的驱动类
    String url="jdbc:mysql://localhost:3306/album"; //连接数据库,album为数据库名称
    String name="root";                             //连接mysql的用户名
    String pwd="root";                              //连接mysql的密码
    try{
      Class.forName(driver);
      Connection conn=DriverManager.getConnection(url,name,pwd);//获取连接对象
      return conn;
    }catch(ClassNotFoundException e){
      e.printStackTrace();
      return null;
    }catch(SQLException e){
      e.printStackTrace();
      return null;
    }
  }
  public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs){
    try{
      if(rs!=null){
        rs.close();
      }
    }catch(SQLException e){
      e.printStackTrace();
    }
    try{
      if(ps!=null){
        ps.close();
      }
    }catch(SQLException e){
      e.printStackTrace();
    }
    try{
      if(conn!=null){
        conn.close();
      }
    }catch(SQLException e){
      e.printStackTrace();
    }
  }
  public static void main(String[] args) throws SQLException
  {
    Connection cc=JDBCUtlTool.getConnection();
    if(!cc.isClosed())
    System.out.println("Succeeded connecting to the Database!");  //连接成功提示
    Statement statement = cc.createStatement();
    String sql = "select * from t_users";                         //从表t_users里获取内容
    ResultSet rs = statement.executeQuery(sql);
    while(rs.next()) {
      System.out.println(rs.getString("id")+"");                  //输出t_user表里的id
    }
  }
}

测试结果:

PS: 如果直接复制我的代码也许会出错, 可能需要导入一些包,

滴!!! 我移植到我的myeclipse时就遇到导入包的问题, 解决办法如下:

赋值mysql-connector-5.1.8-bin.jar到lib下,就可以啦.

下载地址: https://download.csdn.net/download/qq_37832932/10365068

或者在myeclipse下导入某些包, 本人尝试多次均失败, 如有小伙伴知道可以告诉我哦, 谢谢啦^_^.

也可以参考我的错误解决的博客.

    


猜你喜欢

转载自blog.csdn.net/qq_37832932/article/details/80030875