public class ConnectDTUINFOTable
{
static Connection con;
static Statement stmt;
public static void doConnect() throws SQLException
{
String JDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String connectDB = "jdbc:sqlserver://#{sqlServer的ip:port};DatabaseName=#{数据库名字}";
try {
Class.forName(JDriver);
} catch (ClassNotFoundException e) {
System.out.println("加载数据库引擎失败");
System.exit(0);
}
System.out.println("数据库驱动成功");
try {
String user = "#{用户名}";
String password = "#{密码}";
con = DriverManager.getConnection(connectDB, user, password);
System.out.println("连接数据库成功");
stmt = con.createStatement();
}
catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库连接错误");
System.exit(0);
}
ResultSet rs = stmt.executeQuery("SELECT * FROM #{数据表} ");
while (rs.next()) {
System.out.println(rs.getString("id") + "\t"
+ rs.getString("站点名称") +
"\t\t\t" + rs.getString("区域")
+ "\t\t\t" +rs.getString("类型")
+ "\t\t\t" +rs.getString("站点")
+ "\t\t\t" +rs.getString("项目")
+ "\t\t\t" +rs.getDouble("上限")
+ "\t\t\t" +rs.getString("下限")
+ "\t\t\t" +rs.getString("单位")
+ "\t\t\t" +rs.getString("数据类型")
);
}
System.out.println("读取完毕");
stmt.close();
con.close();
System.out.println("数据库关闭成功!");
}
public static void main(String[] args) {
try {
doConnect();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- resultset.getString()的两种方法
- getString(int columnIndex),数据表中的列序号
Connection conn = ……
String sql = "SELECT username,pwd FROM myTable";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}
- getString(String columnLabel),数据表中列名称或别名
Connection conn = ……
String sql = "SELECT username,pwd FROM myTable";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getString("username"));
System.out.println(rs.getString("pwd"));
}