zoukankan      html  css  js  c++  java
  • JDBC连接几种常用数据库的方法

    import java.sql.*;
    
    public class SqlTest {
    	/**
    	 * @param args
    	 * @throws ClassNotFoundException
    	 * @throws IllegalAccessException
    	 * @throws InstantiationException
    	 * @throws SQLException
    	 */
    	public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
    		// TODO Auto-generated method stub
    
    		 //JDBC-mysql 连接驱动字符串
    		    String driverClass="com.mysql.jdbc.Driver";
    		    String url = "jdbc:mysql://localhost:3306";				
                      
    		  //此为NO-DSN方式,直接连接Access数据库 
                      //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    		  //String dburl ="jdbc:odbc:driver={Microsoft Access Driver       (*.mdb)};DBQ=test.mdb";
    		//Connection conn=DriverManager.getConnection(dburl);
    
    		  //JDBC-ODBC 连接驱动字符串
    		 /* String driverClass="sun.jdbc.odbc.JdbcOdbcDriver";
    		    String url="jdbc:odbc:odbc_db";*/		
    		
    		 //JDBC-sqlserver 连接驱动字符串
    		   /* String driverClass="com.microsoft.sqlserver.jdbc.SQLServerDriver";
    		    String url="jdbc:sqlserver://localhost:1433;user=sa;password=sa";*/
    		
    			Connection con=null;
    			Statement st=null;  
    			
    
    			
    			try {	
    			Class.forName(driverClass);			
    			con = DriverManager.getConnection(url, "root", "123");
    			//con=DriverManager.getConnection(url);
    			st = con.createStatement();
    			st.executeUpdate("use test");
    			//st.executeUpdate("drop table bookinfo");
    			st.executeUpdate("create table bookinfo(id INT not null primary key,title VARCHAR(50) not null,author VARCHAR(50) not null)");
    			st.addBatch("insert into bookinfo values(1,'入门到精通','张三')");
    			st.executeBatch();	
    			
    			String sqlStr = "select * from bookinfo";	
    			ResultSet rs = st.executeQuery(sqlStr);
    			while (rs.next()) {
    				System.out.print(rs.getString(1) + " ");
    				System.out.print(rs.getString(2) + " ");
    				System.out.print(rs.getString(3) + " ");
    			}
    			System.out.println("添加成功");
    			rs.close();
    			st.close();
    			con.close();
    			
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			if(st!=null)
    			{
    			   try{
    				   st.close();
    			   }catch(SQLException e){
    				   e.printStackTrace();
    			   }
    			   st=null;
    			}
    			if(con!=null)
    			{
    				try{
    					con.close();
    				}catch(SQLException e)
    				{
    					e.printStackTrace();
    				}
    				con.close();
    			}
    		}
    	}
    
    }
    连接sqlserver 2000或则2005采用,sqljdbc.jar驱动包,连接mysql的需要mysql jdbc驱动包

  • 相关阅读:
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    网络爬虫的相关综述
    HTTP协议和几种常见的状态码
    在php中,如何将一个页面中的标签,替换为用户想输出的内容
    php学习第一讲----php是什么?
  • 原文地址:https://www.cnblogs.com/yuxuan/p/1915414.html
Copyright © 2011-2022 走看看