1. 新建一个sql.properties文件,内容如下。
driver=com.mysql.jdbc.Driver url=jdbc:mysql://192.168.1.151:3306/irrigation?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT user=root pwd=root |
2. 使用io读取文件信息。
InputStream in=getClass().getClassLoader().getResourceAsStream("sql.properties"); Properties properties=new Properties(); try { properties.load(in); String driver=properties.getProperty("driver"); String url=properties.getProperty("url"); String user=properties.getProperty("user"); String password =properties.getProperty("pwd"); } |
3. 使用读取的信息连接数据库,执行sql并保存结果集。
//加载驱动程序 Class.forName(driver); //1.getConnection()方法,连接MySQL数据库!! con = DriverManager.getConnection(url,user,password); //2.创建dosql类对象,用来执行SQL语句!! Statement dosql = con.createStatement(); //3.ResultSet类,用来存放获取的结果集!! ResultSet rs = dosql.executeQuery(sql); |
4. 第3步的异常可在第2步里try{}catch{}。