JDBC
/** * jdbc建立数据库连接 */ public static void main(String[] args) { try { //1.注册驱动 //DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver"); //2.建立连接 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "123456"); //3.创建statement Statement st = conn.createStatement(); //4.执行查询 String sql = "select * from tt_test"; ResultSet rs = st.executeQuery(sql); //5.遍历查询每一条数据 while(rs.next()){ String name = rs.getString("name"); int age = rs.getInt("age"); System.out.println("name="+name+"--------"+"age="+age); } rs.close(); st.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
![](https://img2018.cnblogs.com/blog/964203/201809/964203-20180921150940921-953695331.png)
/** * jdbc使用properties配置文件连接 */ public static void main(String[] args) throws IOException { String driverClass; String url; String name; String password; //1.创建一个属性配置对象 Properties properties = new Properties();
//对应文件位于工程根目录
InputStream is = new FileInputStream("jdbc.properties");
//使用类加载器,去读取src底下的资源文件(对应文件位于src目录下) InputStream is = Test2.class.getClassLoader().getResourceAsStream("jdbc.properties"); //导入输入流 properties.load(is); //读取属性 driverClass = properties.getProperty("driverClass"); url = properties.getProperty("url"); name = properties.getProperty("name"); password = properties.getProperty("password"); try { //1.注册驱动 //DriverManager.registerDriver(new com.mysql.jdbc.Driver()); Class.forName(driverClass); //2.建立连接 Connection conn = DriverManager.getConnection(url, name, password); //3.创建statement Statement st = conn.createStatement(); //4.执行查询 String sql = "select * from tt_test"; ResultSet rs = st.executeQuery(sql); //5.遍历查询每一条数据 while(rs.next()){ String name1 = rs.getString("name"); int age = rs.getInt("age"); System.out.println("name="+name1+"--------"+"age="+age); } rs.close(); st.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } }
public void testInsert() throws Exception{ Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "123456"); Statement st = conn.createStatement(); //插入、删除、更新类似 String sql = "insert into tt_test (name,age) VALUES('eee',22)"; int result = st.executeUpdate(sql); if(result > 0){ System.out.println("添加成功"); } }