jdbc数据库基础

1.在数据库中新建数据表
CREATE TABLE t_user(
ID NUMBER,
NAME VARCHAR2(32),
age VARCHAR2(5),
birth DATE
);
SELECT * FROM t_user;
CREATE SEQUENCE seq_user;
INSERT INTO t_user VALUES(
seq_user.nextval,'zhangsan','23',SYSDATE);
COMMIT;

2.新建java工程

3.导入jdbc所需要的jar包 jar包路径“D:\oracle\product\11.2.0\dbhome_1\jdbc\lib”文件夹下

右键工程-新建folder,用lib命名,然后将jar包导入,再build path

4.以对数据库做一个查询操作为例,进行jdbc的测试

public static void query()throws ClassNotFoundException, SQLException {

//1.加载驱动

Class.forName("oracle.jdbc.driver.OracleDriver");

//2.定义连接URL

String url="jdbc:oracle:thin:@localhost:1521:orcl";

//3.获取数据库的连接

Connection conn = DriverManager.getConnection(url,"scott","tiger");

//4.创建statement对象

Statement st = conn.createStatement();//用来执行sql语句,返回结果集

//5.执行查询或更新

String sql = "select id,name,age,birth from t_user";

ResultSet rs =sql.executeQuery(sql);

//6.遍历结果集对象

while(rs.next()){

int id =rs.getInt("id");

String name=rs.getString("name");//这里的变量名可以随便起,但是列名一定不要写错

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class UserDao {

	public static void query() throws ClassNotFoundException, SQLException{
		Class.forName("oracle.jdbc.driver.OracleDriver");
		String url="jdbc:oracle:thin:@localhost:1521:orcl";
		Connection conn=DriverManager.getConnection(url,"scott","tiger");
		String sql="select id,name,age,birth from t_user";
		Statement st =conn.createStatement();
		ResultSet rs =st.executeQuery(sql);
		while(rs.next()){
			int id = rs.getInt("id");
			String name = rs.getString("name");
			String age=rs.getString("age");
			Date birth=rs.getDate("birth");
			System.out.println(id+"$"+name+"$"+age+"$"+birth);
			conn.close();
			st.close();
			rs.close();
			
		}
	}
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		query();
		
		
	}

}

String age = rs.getString("age");

Date birth =rs.getDate("birth");

system.out.println(id+":"+name+":"+age+":"+birth);

//7.关闭连接释放资源

rs.close();

st.close();

conn.close();

}

}

public static void main (String[] args) ClassNotFoundException, SQLException{

query();

}

需要注意的是:

1.千万不要忘记导入jar包

2.建立连接的时候会抛出异常


你可能感兴趣的:(Java学习)