package com.zhsh.sql.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SQLTest {
/**
* @param args
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException {
// TODO Auto-generated method stub
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//加载JDBC驱动
String urlName = "jdbc:sqlserver://localhost:1433; DatabaseName=simpletest";//连接服务器和数据库
String userName = "AUTEK";
String pass = "FLYVIDEO";
Connection conn;
PreparedStatement ps;
ResultSet rs;
try {
Class.forName(driverName);
conn = DriverManager.getConnection(urlName,userName,pass);
System.out.println("Connection Sucessful!");
String sql = "select * from users";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
System.out.println(rs.getString("username"));
}
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
}finally{
}
}
}
注意:
1.因为SQLexpress服务器默认是禁用的并且端口号没有配置,所以要进行重新设置
2.在sql server 2000 中加载驱动和URL路径的语句是
String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
String dbURL = "jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sample";
而sql server 2005 中加载驱动和url的语句则为
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=sample";