`

JDBC连接数据库--入门

阅读更多
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class SimpleJDBCTest {

public static final String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";

public static final String drivername = "com.microsoft.jdbc.sqlserver.SQLServerDriver";

public static final String user = "sa";

public static final String password = "sa";

public static void main(String[] args) {
   String sql = "select title,price from titles";
   Connection connection = null;
   Statement statement = null;
   ResultSet resultSet = null;
   try {
    Class.forName(drivername);
    System.out.println("加载驱动成功!");
    connection = DriverManager.getConnection(url, user, password);
    System.out.println("连接数据库成功!");
    statement = connection.createStatement();
    resultSet = statement.executeQuery(sql);
    while (resultSet.next()) {
     System.out.println("书名:" + resultSet.getString("title") + "定价:"
       + resultSet.getDouble("price"));
    }
    resultSet.close();
    statement.close();
    connection.close();

   } catch (Exception e) {
    e.printStackTrace(System.out);
   } finally {
    try {
     if (resultSet != null) {
      resultSet.close();
     }
    } catch (Exception e) {
     System.err.println("关闭ResultSet时发生异常!");
    }
    try {
     if (statement != null) {
      statement.close();
     }
    } catch (Exception e) {
     System.err.println("关闭statement时发生异常!");
    }
    try {
     if (connection != null) {
      connection.close();
     }
    } catch (Exception e) {
     System.err.println("关闭connection时发生异常!");
    }
   }
}
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics