📄 connectiondemo2.java~16~
字号:
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.io.IOException;
/**
* <p>Title: JAVA连接SQL Server数据库的简单例子2</p>
* <p>Description: 第四章例子</p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: </p>
* @author 苏年乐
* @version 1.0
*/
public class ConnectionDemo2 {
public ConnectionDemo2() {
}
void display() {
Connection con = null;
String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=MyDB";
try {
//装入驱动程序
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
System.out.println("成功加载驱动程序");
//建立连接
String username="sa";
String password="";
con = DriverManager.getConnection(url,username,password);
System.out.println("成功连接数据库");
//创建语句
Statement stmt = con.createStatement();
//用于保存查询结果的变量声明与定义
int id;
String text;
int age;
//建立ResultSet
ResultSet rs;
String strSQL= "Select * From Person";
rs = stmt.executeQuery(strSQL);
if (rs.next()) {
do {
id=rs.getInt(1);
System.out.print("ID:" + id);
text = rs.getString(2);
System.out.print(" 姓名:" + text);
text = rs.getString(3);
System.out.print(" 性别:" + text);
age = rs.getInt(4);
System.out.print(" 年龄:" + text);
text = rs.getString("address");
System.out.print(" 地址:" + text);
text = rs.getString("phone");
System.out.println(" 电话:" + text);
}
while (rs.next());
}
else {
System.out.println("没有数据");
}
} //end of try
catch (ClassNotFoundException e) {
System.out.println(e);
}
catch (SQLException e) {
System.out.println(e);
}
finally {
try {
//关闭连接
if (con != null) {
con.close();
}
}
catch (SQLException e) {
System.out.println(e);
}
}
}
public static void main(String[] args) {
ConnectionDemo2 app = new ConnectionDemo2();
app.display();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -