jdbc数据库连接
1、比如sun公司开发的java链接数据库方法:class connection{public Connection getConnection(url,username,password);//抽象方法由sun公司实现}DiverManger.getConnection();建立java与数据库链接JDBC接口和数据库厂商的实现:DriverManger接口:加载驱动Connection 接口:建立连接statement 接口:编译sql语句
2、JDBC工作原理和工作过程:1.加载驱动mysql 驱动接口:com.mysql.jdbc.Driveroracle 驱动接口:oracle.jdbc.driver.OracleDriver2.建立连接:通过DriverManger.getConnection(url,user,password);mysql url:jdbc:mysql://ip地址:数据库名3.编译执行sql语句String sql=“SQL语句”;statement stmt=con.createSatement(sql);4.处理结果集ResultSet rs=stmt.excuteQuery();ResultSet rs=stmt.excuteUpdate();5.关闭连接con=close();
3、public class Demo3 {public static void main(String[] args) {try {Class.forName("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {System.out.println("加载失败!");}Connection con=null;Statement stmt=null;ResultSet rs=null;try {
4、con=DriverManager.getConnection("jdbc:mysql://localhost:3306/jav锾攒揉敫a1707","root","123456");//编写执行sql语句stmt=con.createStatement();//处理结果集rs=stmt.executeQuery("select * from emp");//迭代的方式处理结果集while(rs.next()){System.out.println("empno"+rs.getInt("empno")+",ename"+rs.getString("ename"));}} catch (SQLException e) {System.out.println("连接失败!");}finally{try {con.close();} catch (SQLException e) {System.out.println("关闭失败!");}}}}
5、import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.util.Properties;/*** * @author Administrator* */public class DBUtil {private static Properties properties = new Properties();private static String driver = null;private static String url = null;private static String username = null;private static String password = null;
6、// 静态代码块读取配置文件中的信息static {try {properties.load(D幞洼踉残BUtil.class.getClassLoader().getResourceAsStream("db.properties"));driver = properties.getProperty("driver");url = properties.getProperty("url");username = properties.getProperty("username");password = properties.getProperty("password");try {Class.forName(driver);} catch (ClassNotFoundException e) {System.out.println("加载驱动失败!");}} catch (IOException e) {System.out.println("读取文件失败");}}//建立连接方法public static Connection getConnection() throws SQLException {return DriverManager.getConnection(url, username, password);}//关闭连接的方法public static void closeConnection(Connection con){try {con.close();} catch (SQLException e) {System.out.println("关闭连接失败!");}}}