maven利用jtds,c3p0连接SqlServer

转载请注明出处:http://coffeehot.iteye.com/admin/blogs/2184881

由于maven无法直接使用sqljdbc4.jar来连接SqlServer,因此使用jtds和c3p0来替代。

具体做法:

1. 加入pom依赖

 

   
        net.sourceforge.jtds
        jtds
        1.3.1
    
    
        c3p0
        c3p0
        0.9.1.2
    

 

 

2. 在src/main/resources下加入c3p0-config.xml



    
        net.sourceforge.jtds.jdbc.Driver

        jdbc:jtds:sqlserver://localhost:1433/mydb
        

        sa

        Admin123

        50

        100

        50

        1000
       
    
   
   
    

        net.sourceforge.jtds.jdbc.Driver

        jdbc:jtds:sqlserver://127.0.0.1:1433/mydb
        

        sa

        Admin123

        30000

        30

        10

        30

        100

        10

        200

    

 

3.测试

public class Test
{

private static HashMap connMap = new HashMap();

public static void main(String[] args) throws Exception
{
testConn();
}

public static void testConn() throws Exception
{
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Connection ct = DriverManager.getConnection("jdbc:sqlserver://localhost:1433; DatabaseName=mydb","sa","Admin123");

Connection ct = getConnection("mydb");
// Connection ct = getDefaultConnection();
PreparedStatement st = ct.prepareStatement("select id, name from dbo.test_conn");
st.execute();
ResultSet rs = st.getResultSet();
while(rs.next())
{
System.out.println("result: " + rs.getString(1));
}
}

public static Connection getConnection(String name){

Connection conn = null;
ComboPooledDataSource ds =null;
if(name==null||name.equals(""))
return null;

if(connMap.keySet().contains(name)){
ds = (ComboPooledDataSource)connMap.get(name);
}else{
ds = new ComboPooledDataSource(name);
}
try {
if(ds==null){
return null;
}
conn = ds.getConnection();
connMap.put(name, ds);
} catch (SQLException e) {
}
return conn;
}

public static Connection getDefaultConnection(){
ComboPooledDataSource ds = new ComboPooledDataSource();
try{
return ds.getConnection();
}catch(SQLException e){
}
return null;
}

}

 

你可能感兴趣的:(sqlserver,maven,c3p0)