JDBCがいくつかの一般的なデータベースに接続する方法
2603 ワード
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