import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Collection; import java.util.Properties; public class JDBC { private Properties p = new Properties(); private static String driver; private static String url; private static String user; private static String psw; public static void main(String[] args) throws Exception { new JDBC().run(); } void run() throws Exception{ p.load(this.getClass().getResourceAsStream("properties"));//利用反射获取calss信息 driver =p.getProperty("driver"); //把获取信息赋值给变量 url =p.getProperty("url"); //把获取信息赋值给变量
user =p.getProperty("user");//把获取信息赋值给变量 psw =p.getProperty("pwd"); //把获取信息赋值给变量Class.forName(driver); Connection c ; c= DriverManager.getConnection(url,user,psw); Statement sta = c.createStatement(); String sql = "select ename from emp"; ResultSet rs=sta.executeQuery(sql); while(rs.next()){ System.out.println(rs.getString(1)); } } }
Properties//配置文件 new File
driver=com.mysql.jdbc.Driver url=jdbc:mysql://122.114.147.148:3306/java0613 user=java0613 pwd=java0613
时间: 2024-10-02 09:36:57