jdbc
import java.sql.DriverManager; import java.sql.Connection; import java.sql.Statement; public class Type { static { try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//驱动为sun提供的 加载驱动 这个驱动是所有数据库通用的 这是一种jdbc的连接方式 “里为jdbc驱动名” }catch(ClassNotFoundException e) { e.printStackTrace(); } } public static void main(String []args) throws Exception{ Connection con = DriverManager.getConnection("jdbc:odbc:odb_1","root","root");//url jdbc:odbc:数据源名 用户名 密码 建立连接 最耗费资源的部分 String sql = "select * from user"; Statement stmt = con.createStatement();//发送语句 ResultSet rs = stmt.executeQuery(sql);//查询是executeQuery,其余executeUpdate while(rs.next()){ int id = rs.getInt("Id"); String username = rs.getString("username"); String password = rs.getString("password"); Timestamp barthday = rs.getTimestamp("barthday"); System.out.println(id+" "+username+" "+password+" "+barthday); } } }
package com.myivtec.demo2; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Demo2 { static { try { Class.forName("com.mysql.jdbc.Driver");//type4不同的数据库需要不同的驱动 和上一种不同的连接方法不同数据库不同 } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static void main(String[] args) { Connection con = null; Statement stmt = null; ResultSet rs = null; try { //不同的数据库url也不一样 con = DriverManager.getConnection("jdbc:mysql://localhost/myivtec", "root", "root"); stmt = con.createStatement(); String sql = "select * from user"; rs = stmt.executeQuery(sql); while(rs.next()) { int id = rs.getInt(1);//getXXX 可以传递列明 或者 是 索引号码 String username = rs.getString(2);//2代表表中第几列 String psw = rs.getString("password"); String age = rs.getString(4);//getString可以取所有的文本类型 String sex = rs.getString(5); String birthday =rs.getString(6); System.out.println(id+" "+username+" "+psw+" "+age+" "+sex+" "+birthday); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { rs.close(); stmt.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }





posted on 2013-12-02 19:23 weiguoyuan 阅读(207) 评论(0) 收藏 举报
浙公网安备 33010602011771号