JDBC连接数据库
2018-07-20 来源:open-open
[Java]代码
package com.ant.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author 杨俊宁
*
*/
public class Connector {
Connection con;
PreparedStatement pstmt;
ResultSet rs;
private final String user = "root";
private final String password = "jun19931129";
private final String driver = "com.mysql.jdbc.Driver";
private final String url = "jdbc:mysql://localhost:3306/ant?useUnicode=true&characterEncoding=gbk";
/**
* 该方法依次完成加载驱动??接数据库的任务
* @return con
*/
public Connection getConnection()
{
Connection con = null;
try {
Class.forName(driver);
//System.out.println(">>>>>>>>>JDBC Driver Manager加载成功);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println(">>>>>>>>>JDBC Driver Mana");
}
try {
con = DriverManager.getConnection(url, user, password);
//System.out.println(">>>>>>>>>数据库连接成功!");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库连接失败!");
}
return con;
}
/**
* 该方法依次关闭处理查询结果集对象rs、预处理语句对象pstmt、连接数据库对象con
* @return
*/
public void closed()
{
try{
if(rs!=null)
rs.close();
System.out.println("对象rs已关闭!");
}catch(SQLException e){
System.out.println("关闭rs对象异常");
e.printStackTrace();
}
try{
if(pstmt!=null)
pstmt.close();
System.out.println("对象pstmt已关闭!");
}catch(SQLException e){
System.out.println("关闭pstm对象失败");
e.printStackTrace();
}
try{
if(con!=null){
System.out.println("对象con已关闭!");
con.close();
}
}catch(SQLException e){
System.out.println("关闭con对象失败");
e.printStackTrace();
}
con=null;
}
}
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐