//本程序连接的是sql server 2005,与连接sql server 2000有点不同:driverName和URL都不同
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class create{
public void getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException
{
Statement stmt = null;
Connection dbConn;
ResultSet rs;
String user="sa";
String pass="";
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=tempdb";
try{
Class.forName(driverName).newInstance();
System.out.println("ok");
dbConn = DriverManager.getConnection(URL,user,pass);
System.out.println("Connection Successful!");
stmt = dbConn.createStatement(); // 获得执行SQL语言的容器
rs=dbConn.getMetaData().getTables(null, null, "testTb", null);
if(rs.next()){
System.out.println("testTb存在!咱现在把它删了吧!");
stmt.executeUpdate("drop table testTb");
System.out.println("回头再看看,没了吧?");
}
else{
System.out.println("testTb不存在!咱现在就创建它吧!");
stmt.executeUpdate("create table testTb(cola int,colb char(3),row int)");
System.out.println("回头再看看,有了吧?");
}
} catch (SQLException e) {
System.out.println("出错啦!");
}
}
public static void main(String [] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException
{
create conn=new create();
conn.getConnection();
}
}
本文提供了一个使用Java连接SQL Server 2005并进行基本操作的示例程序,包括检查和创建数据库表。示例中详细展示了如何加载驱动、建立连接、执行SQL语句等步骤。

5043

被折叠的 条评论
为什么被折叠?



