实现了调用数据库的数据
package Demo;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcText {
public static void main(String[] args) {
Connection dbConn = null;
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; // 加载JDBC驱动
// 连接服务器和数据库ServletUser
String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=ServletUser";
String userName = "sa"; // 默认用户名
String userPwd = "123456"; // 密码
String sqlStr="select CustomerID, CompanyName, ContactName from Customers";
try {
Class.forName(driverName);
dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
System.out.println("Connection Successful!"); // 如果连接成功
System.out.println(userName);
System.out.println("类实例化成功!");
Connection con = DriverManager.getConnection(dbURL, userName, userPwd);
System.out.println("创建连接对像成功!");
Statement st = con.createStatement();
System.out.println("创建Statement成功!");
ResultSet rs = st.executeQuery(sqlStr);
System.out.println("操作数据表成功!");
System.out.println("----------------!");
while(rs.next()) {
System.out.print(rs.getString("CustomerID") + " ");
System.out.print(rs.getString("CompanyName") + " ");
System.out.println(rs.getString("ContactName"));
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}finally{
//进行资源的释放
if(dbConn!=null){
try {
dbConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}