【www.gdgbn.com--mysql教程】
连接sqlserver 2000或则2005采用,sqljdbc.jar驱动包,连接mysql教程的需要mysql 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();
}
}
}}