Guest User

Untitled

a guest
Nov 18th, 2017
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.82 KB | None | 0 0
  1. package test;
  2.  
  3. import java.sql.*;
  4.  
  5. public class test {
  6. public static void main(String[] args) {
  7. //声明Connection对象
  8. Connection con;
  9. //驱动程序名
  10. String driver = "com.mysql.jdbc.Driver";
  11. //URL指向要访问的数据库名login
  12. String url = "jdbc:mysql://192.168.100.71:6033,192.168.100.72:6033,192.168.100.73:6033/sbtest?failOverReadOnly=false&secondsBeforeRetryMaster=0&queriesBeforeRetryMaster=0";
  13. //MySQL配置时的用户名
  14. String user = "test";
  15. //MySQL配置时的密码
  16. String password = "111111";
  17. //遍历查询结果集
  18. try {
  19. //加载驱动程序
  20. Class.forName(driver);
  21. //1.getConnection()方法,连接MySQL数据库!!
  22. con = DriverManager.getConnection(url, user, password);
  23. if (!con.isClosed())
  24. System.out.println("Succeeded connecting to the Database!");
  25. //2.创建statement类对象,用来执行SQL语句!!
  26. Statement statement = con.createStatement();
  27. //要执行的SQL语句
  28. String sql = "select count(*) from sbtest1"; //从建立的login数据库的login——message表单读取数据
  29. //3.ResultSet类,用来存放获取的结果集!!
  30. ResultSet rs = statement.executeQuery(sql) ;
  31. System.out.println("-----------------");
  32. System.out.println("执行结果如下所示:");
  33. System.out.println("-----------------");
  34. Integer id = null;
  35. Integer k = null;
  36. String c = null;
  37. String pad = null;
  38. while (rs.next()) {
  39. //获取stuname这列数据
  40. id = rs.getInt(id);
  41. //获取stuid这列数据
  42. k = rs.getInt(k);
  43. c = rs.getString(c);
  44. pad = rs.getString(pad);
  45. //首先使用ISO-8859-1字符集将name解码为字节序列并将结果存储新的字节数组中。
  46. //然后使用GB2312字符集解码指定的字节数组。
  47. //name = new String(name.getBytes("ISO-8859-1"), "gb2312");
  48. //输出结果
  49. System.out.println(id + "\t" + k + "\t" + c + "\t" + pad );
  50. }
  51. rs.close();
  52. con.close();
  53. } catch (ClassNotFoundException e) {
  54. //数据库驱动类异常处理
  55. System.out.println("Sorry,can`t find the Driver!");
  56. e.printStackTrace();
  57. } catch (SQLException e) {
  58. //数据库连接失败异常处理
  59. e.printStackTrace();
  60. } catch (Exception e) {
  61. // TODO: handle exception
  62. e.printStackTrace();
  63. } finally {
  64. System.out.println("数据库数据成功获取!!");
  65. }
  66. }
  67.  
  68. }
Add Comment
Please, Sign In to add comment