java使用jdbc连接数据库步骤

// 1.加载驱动类,这里是用oracle数据库的驱动

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

// 2.获取连接

Connection    conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "账号", "密码");

// 3.创建statment(有sql注入的危险)或者preparestatment(预编译,没注入危险)

Statement      stmt = conn.createStatement();

// 4.执行sql取得结果executeQuery查询或者executeUpdate修改

ResultSet        rs = stmt.executeQuery("select * from emp ");

最后要关闭资源rs,stmt, conn

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

public class JDBCTest {

	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			// 1.加载驱动类
			Class.forName("oracle.jdbc.driver.OracleDriver");
			// 2.获取连接
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "数据库账号", "密码");
			// 3.创建statment或者preparestatment
			stmt = conn.createStatement();
			// 4.执行sql取得结果
			rs = stmt.executeQuery("select * from emp ");
			while (rs.next()) {
				String ename = rs.getString("ename");
				System.out.println(ename);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 5.关闭资源
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

}


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页