Java连接SQLServer2008(常用数据库连接三)
1.确定安装好SQLServer2008数据库登录数据库中建立一个新数据库,并创建一张表,内容如下图所示:
2.eclipse或者Myeclipse中建立Java工程,导入连接sqlserver2008在jar包sqljdbc4.jar,下载地址为http://download.csdn.net/detail/whzhaochao/6414981
3.建立iConn.java接口,代码如下:
package com.zhaochao.dba; import java.sql.Connection; public interface iConn { Connection getConn(); }4.建立连接sqlserver2008类实现iConn接口
代码如下:
注意修改连接数据库的用户名和密码以及数据库名
package com.zhaochao.dba; import java.sql.Connection; import java.sql.DriverManager; public class SQLServerConn implements iConn { private static final String DBDRIVER = "com.microsoft.jdbc.sqlserver.SQLServerDriver" ; private static final String DBURL = "jdbc:sqlserver://localhost:1433;databaseName=zhaochao" ; private static final String DBUSER = "admin" ; private static final String DBPASS = "admin"; private Connection conn=null; @Override public Connection getConn() { // TODO Auto-generated method stub try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); this.conn=DriverManager.getConnection(DBURL, DBUSER, DBPASS); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return this.conn; } }
5.测试连接代码:
package com.zhaochao.dba; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // TestMySQL(); // TestOracle(); // TestDB2(); TestSQLServer(); // TestAccess(); } private static void TestSQLServer() { Connection conn=null; PreparedStatement ps=null; ResultSet rs=null; iConn iconn=new SQLServerConn(); conn=iconn.getConn(); String sql="select * from zhaochao"; try { ps=conn.prepareStatement(sql); rs=ps.executeQuery(); while(rs.next()){ System.out.println(rs.getString(1)+"|"+rs.getString(2)+"|"+rs.getString(3)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(conn!=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(ps!=null){ try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(rs!=null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
6.测试结果:
1|admin |admin 2|zhaochao |zhaochao