标题JDBC的使用总共分为几大步骤:
(一)加载数据库驱动
Class.forname(driverClass)
Class.forName("com.mysql.jdbc.Driver") Class.forName("oracle.jdbc.driver.OracleDriver")
(二)获取数据库连接
Connection conn = null;
conn = DriverManager.getConnection(url, username, password);或者
Connection conn=DriverManager.getConnection(url,username,password);
其中url的表达方式:
1、Oracle:jdbc:oracle:thin:@localhost:1521:shen
2、SqlServer:jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=shen
3、MySql:jdbc:mysql://localhost:3306/shen
(三)创造StatementPreparedment对象
1、Statement
JDBC程序中的Statement对象用于向数据库发送SQL语句,创建方法为:
Statement st = conn.creatStatement();
Statement对象常用方法:
方法 含义
executeQuery(String sql) 用于向数据发送查询语句。
executeUpdate(String sql) 用于向数据库发送insert、update或delete语句
execute(String sql) 用于向数据库发送任意sql语句
addBatch(String sql) 把多条sql语句放到一个批处理中。
executeBatch() 向数据库发送一批sql语句执行。
2、PreperedStatement
PreperedStatement是Statement的孩子,它的实例对象可以通过调用:
PreperedStatement st = conn.preparedStatement()
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/tables";
String username = "user";
String password = "123456";
Connection conn=DriverManager.getConnection(url,username,password);
PreperedStatement st = null;
String sql = "select * from user where name=? and password=?";
st = conn.preparedStatement(sql);
st.setString(1,username);
st.setString(2,password);
ResultSet rs = st.executeQuery();//如果有数据,可以进行提取出来
while(re.next()){
System.out.printIn(re.getString("user_name"+"年龄:")+rs.getInt("age"));
}
(四)最后通过ResultSset进行收集,提取
ResultSet rs = st.executeQuery();//如果有数据,可以进行提取出来
while(re.next()){
System.out.printIn(re.getString("user_name"+"年龄:")+rs.getInt("age"));
}
更多操作:增删改查
public class DbUtil{
public static final String URL = "jdbc:mysql//localhost:3306/imooc";
public static final String USER = "root";
public static final String PASSWORD ="123456";
private static Connection conn = null;
static{
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL,USER,PASSWORD);
}catch(Exception e){
e.printStackTrace();
}
}
public static Connection getConnection(){
return conn;
}
}