JDBC创建数据库连接详细代码及注释

版权声明:本文章的所有内容,包括文字、图片,均为原创。转载请注明出处。作者首页:https://blog.csdn.net/songxinfeng1989 https://blog.csdn.net/songxinfeng1989/article/details/81776646

注:完整代码在最后

使用jdbc创建mysql数据库连接

1.从db.properties配置文件中读取数据库连接参数。

db.properties文件内容如下:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/数据库名?useUnicode\=true&characterEncoding\=UTF-8
jdbc.username=用户名
jdbc.password=密码

创建Properties对象

Properties prop = new Properties();

创建输入流

InputStream in = getClass().getResourceAsStream("/db.properties");

加载配置文件   有可能会有io异常需要try  chatch

try {
        prop.load(in);
} catch (IOException e) {
        e.printStackTrace();
  }

声明驱动类

Class jdbcDriverClass;

声明数据库连接

 Connection conn     =    null;

必须添加trycatch 否则创建出现异常后 容易不关闭连接,会一直占用,
try {

加载驱动类

jdbcDriverClass = Class.forName("com.mysql.jdbc.Driver");

//创建驱动

Driver driver = (Driver) jdbcDriverClass.newInstance();

注册驱动

  DriverManager.registerDriver(driver);

//创建连接

conn=(Connection)DriverManager.getConnection(prop.getProperty("jdbc.url"),prop.getProperty("jdbc.username"),prop.getProperty("jdbc.password"));


} catch (Exception e) {

输出错误信息

e.printStackTrace();

创建连接 异常后关闭
          

 if(conn!=null){//如果连接不是null则关闭
      try {
         conn.close();
       } catch (SQLException e2) {
          e2.printStackTrace();//输出错误信息
       }
  }

}
    

完整方法代码如下:

/**
	 * 创建数据库连接
	 * @return
	 */
	private  Connection getConnection() {
		//从db.properties文件中获取数据库连接
		Properties prop = new Properties();//创建Properties对象
    	InputStream in = getClass().getResourceAsStream("/db.properties");//创建输入流
		try {
			prop.load(in);//加载配置文件   有可能会有io异常需要try  chatch
		} catch (IOException e) {
			e.printStackTrace();
		}
		Class jdbcDriverClass;//声明驱动类
		Connection conn 	=	null;//声明数据库连接
		try {//必须添加trycatch 否则创建出现异常后 容易不关闭连接,会一直占用,
			jdbcDriverClass = Class.forName("com.mysql.jdbc.Driver");//加载驱动类
			Driver driver = (Driver) jdbcDriverClass.newInstance();//创建驱动
			DriverManager.registerDriver(driver);//注册驱动
			conn = (Connection) DriverManager.getConnection(prop.getProperty("jdbc.url"),prop.getProperty("jdbc.username"),prop.getProperty("jdbc.password"));//创建连接
		} catch (Exception e) {
			e.printStackTrace();//输出错误信息
			//创建连接 异常后关闭
			if(conn!=null)//如果连接不是null则关闭
				try {
					conn.close();
				} catch (SQLException e2) {
					e2.printStackTrace();//输出错误信息
				}
		}
		return conn;
	}	

猜你喜欢

转载自blog.csdn.net/songxinfeng1989/article/details/81776646