gtxyzz

java连接MySQL,SQL server数据库

gtxyzz 虚拟化 2023-02-26 720浏览 0

  java连接MySQL:  

  首先导入jar包文件:  

 

  java连接MySQL,SQL server数据库

  下载地址:http://download.csdn.net/detail/chongzi321/5703641

  然后:

    

 1        Connection ct = null;  
 2         Statement  sm = null;  
 3         ResultSet rs = null;
 4           
 5         try{     
 6             Class.forName("com.mysql.jdbc.Driver");      
 7             ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf-8","用户名",        "密码"); 
 8             sm = ct.createStatement();
 9             String selectString = "select 字段 from 表名 where 字段 = '属性值'"
10             sm.executeQuery(selectString);
11         }  
12         catch(Exception ex){  
13               System.out.print("失败!"); 
14         }
15          finally{  
16              try{  
17                  if(rs!=null){  
18                      rs.close();  
19                  }  
20                  if(sm!=null){  
21                      sm.close();  
22                  }  
23                  if(ct!=null){  
24                      ct.close();  
25                  }  
26                    
27              }  
28              catch(Exception ex){  
29                    ex.printStackTrace();  
30              }  
31          }  
32

 

   java连接SQL server:

   导入sqljdbc驱动包

   这里有驱动包:http://download.csdn.net/download/u011200062/8361465

   接下来这样写:

    

Connection ct = null;  
        Statement  sm = null;  
        ResultSet rs = null;
 
          try{
               Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                String    url="jdbc:sqlserver://localhost:1433;DatabaseName=数据库名";    
                 String user="sa";                    //登录sql server的用户名和密码
                 String pwd="123456";                 //密码
                    ct=DriverManager.getConnection(url,user,pwd);
                sm = ct.createStatement();
                 rs = sm.executeQuery("select 字段 from 表名 where 字段 = '属性值'");
 
         }  
         catch(Exception ex){  
 
         }  
            
          finally{  
              try{  
                  if(rs!=null){  
                      rs.close();  
                  }  
                  if(sm!=null){  
                      sm.close();  
                  }  
                  if(ct!=null){  
                      ct.close();  
                  }  
                    
              }  
              catch(Exception ex){  
                    ex.printStackTrace();  
              }  
          }  

 

     如果java web连不上SQL Server,就需要打开网络协议,参考这位同学: http://blog.csdn.net/stewen_001/article/details/19553173/

 

 

 

 

 

  

继续浏览有关 数据库技术文章/教程 的文章
发表评论