jdbc

连接mysql数据库,并且通过select语句获得结果。
public static void main(String[] args) throws Exception {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8","", "");
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select * from student"); // 其他的用executeUpdate方法。
			while (rs.next()) {
				System.out.println(rs.getString("name"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
					rs = null; // 这样写的比较完美,close后把它设为null,是为了让垃圾回收器回收它。
				}
				if (stmt != null) {
					stmt.close();
					stmt = null;
				}
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
两种方式加载驱动
1、Class.forName("oracle.jdbc.driver.OracleDriver");
2、new oracle.jdbc.driver.OracleDriver();
两种方法都可以。这个驱动自动向driverManager注册。
 一般不会用new,因为在这里我们需要的时把oracle.jdbc.driver.OracleDriver类加载到内存中,然后自动向driverManager注册。不需要调用其中的方法,所以没有必要去new出来。
new出来会在堆内存开空间,对资源是一种浪费。而通过class.forName,不会在堆开空间。
在JDK1.5之后,其实已经不需要去显式调用Class.forName("com.mysql.jdbc.Driver")了,DriverManager会自动去加载合适的驱动,但是前提是CLASSPATH下必须有驱动jar包
 
 
连接字符串
url比如oracle就是jdbc:oracle:thin:@localhost:1521:orcl
1. Oracle url示例:"jdbc:oracle:thin:@localhost:1521:orcl"
2. Access url示例:"jdbc:odbc:HANFENG"
3. SQL Server url示例:"jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs"
4. DB2 url示例:"jdbc:db2://localhost:5000/sample"
5. Informix url示例:"jdbc:informix-sqli://123.45.67.89:1533/testDB:INFORMIXSERVER=myserver"
6. Sybase url示例:"jdbc:sybase:Tds:localhost:5007/tsdata"
7. MySQL url示例:"jdbc:mysql://localhost/softforum?user=soft&password=soft1234& amp;useUnicode=true&characterEncoding=8859_1"
8. PostgreSQL url示例:"jdbc:postgresql://localhost/soft"
 
要指明数据库的名字
执行select语句要用executeQuery(“”),结果保存到ResultSet 中去。
rs.getString("name")获得name字段里的一条记录,返回一个string
 
执行结束了要把他们都关掉,写在finally里面。
PreparedStatement可以灵活指定sql语句中变量的statement
   pstmt = conn.prepareStatement("insert into student values(?,?)");
   pstmt.setString(1, "sdf");
   pstmt.setString(2, "ss");
   pstmt.executeUpdate();
这样有利于变量类型的控制,用的比较多。
 
 
 
 
 
 
 
 
 
原文地址:https://www.cnblogs.com/tp123/p/6402571.html