JAVA JDBC数据库驱动类的写法
JAVA连接数据库分为两种方式,直连(jdbc)与桥连(odbc,需要在本地架设数据源)
今天我简单讲下JDBC的连接方法
我以MSSQL为例
首先把jar包添加到项目中(不会的留言)
Jar包下载:
sql2005jdbc.jar 如果你使用的JDK为6.0或者更改,您可能需要使用
sqljdbc4.jar驱动类
下面新建一个类
写入以下内容即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | import java.sql.*; /** * @author Harde * */ public class ConnectionManager { /** * */ public ConnectionManager() { // TODO Auto-generated constructor stub } public static final String DRIVER_CLASS = "com.microsoft.sqlserver.jsdc.SQLServerDriver"; public static final String DRIVER_URL = "jdbc:sqlserver://localhost:1433;DatabaseName=Storage"; public static final String USERNAME = "数据库用户名"; public static final String PASSWORD = "数据库用户的密码"; //获得数据库连接 public Connection GetConnection() { Connection con=null; try { Class.forName(DRIVER_CLASS); try { con = DriverManager.getConnection(DRIVER_URL,USERNAME,PASSWORD); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return con; } //关闭数据库连接 public void closeConnection(Connection con){ if(con!=null){ try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //关闭结果集 public void closeResultSet(ResultSet rs){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //关闭Statement数据库操作对象 public void closeStatement(Statement st){ if(st!=null){ try { st.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //关闭PreparedStatement数据库操作对象 public void closePreparedStatement(PreparedStatement ps){ if(ps!=null){ try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } |

没有评论▼