jdbc连接数据库和jdbc-odbc桥接方式连接数据库

//这种方式为jdbc直接连接,需要添加jar文件
1
package com.howe2; 2 import java.sql.*; 3 4 public class test2 { 5 public static void main(String [] args) 6 { 7 PreparedStatement ps = null; 8 Connection con = null; 9 try 10 { 11 //1. 加载驱动 12 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 13 //2. 获得连接 14 con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName = howe", "sa", "sa"); 15 //3. 创建PreparedStatement 16 ps = con.prepareStatement("insert into teacher values(?,?,?)");//一般用? 表示 17 //给?赋值 18 ps.setString(1, "t010"); 19 ps.setString(2, "wek"); 20 ps.setString(3, "Shanghai"); 21 //执行 22 int i = ps.executeUpdate(); 23 if(i == 1) 24 { 25 System.out.println("insert OK"); 26 } 27 else 28 System.out.println("not OK"); 29 }catch(Exception e) 30 { 31 e.printStackTrace(); 32 } 33 finally 34 { 35 try { 36 //关闭资源 37 if(ps != null) 38 ps.close(); 39 if(con != null) 40 con.close(); 41 } catch (SQLException e) { 42 // TODO Auto-generated catch block 43 e.printStackTrace(); 44 } 45 } 46 } 47 }

 这种方式为jdbc-odbc桥接的方式,不需要添加jar文件,但是需要配置数据源,配置数据源的步骤: 控制面板-> 系统和安全->管理工具->数据源(ODBC),然后双击打开,在用户(DSN)下带你及添加, 选择SQL Server, 然后输入一个名字,描述不用输入,服务器填“localhost”或者".", 点击下一步,选择数用用户名和密码的SQL Server验证,然后输入登录数据库时的用户名和密码,如果连接不上,出现错误的话,就要点客户端配置,把动态选择端口去掉,默认1433端口,这个前提是1433端口已经打开,可以在cmd下用netstat -an命令查看1433端口是否打开,如果没有打开的话,再去配置SQL Server的TCP/IP, 然后完成了之后,就简单了,下面是代码:

 1 package com.howe;
 2 import java.sql.*;
 3 public class test1 {
 4 
 5     public static void main(String[] args) {
 6         Connection con = null;
 7         Statement sm = null;
 8         try
 9         {
10             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
11             con = DriverManager.getConnection("jdbc:odbc:mytest", "sa", "sa");
12             sm = con.createStatement();
13             
14             int result = sm.executeUpdate("insert into teacher values('t008','zhang','qingdao')");
15             if(result == 1)
16                 System.out.println("insert success");
17             else
18                 System.out.println("insert error");
19             
20         }catch(Exception e)
21         {
22             e.printStackTrace();
23         }finally
24         {
25             //close resource
26             try {
27                 if(sm != null)
28                     sm.close();
29                 if(con != null)
30                     con.close();
31             } catch (SQLException e) {
32                 // TODO Auto-generated catch block
33                 e.printStackTrace();
34             }
35         }
36 
37     }
38 
39 }
原文地址:https://www.cnblogs.com/Howe-Young/p/4082205.html