数据库的连接主要分为七步:
Connection con = null;
Statement stmt = null;
第一步:
/*
* 1.导包
* a.将对应数据库的驱动包拷贝到项目中
* b.在驱动包上右击->Build Path ->Add to Build Path
*/
第二步:
//2.加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
第三步:
/*
* 3.创建连接
* 第一个参数要远程访问的数据库的URL:
* jdbc:oracle:thin:@<要访问的数据库服务器所在的IP地址>:<数据库服务器所占用的端口号>:<要访问的数据库的库名>
* 第二个参数登入数据库的用户名
* 第三个参数登入数据库的密码
* 127.0.0.1也是本地IP
*/
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:**数据库名**", "**用户名**", "**密码**");
第四步:
//4.创建执行语句块
stmt = con.createStatement();
String sql = "insert into dept values(60,'研发部',8606)";
第五步:
//5.执行语句块,获取结果或结果集
int result = stmt.executeUpdate(sql);//获取语句执行后所影响的数据的行数
第六步:
//6.处理结果
if(result > 0) {
System.out.println("部门信息添加成功...");
}else {
System.out.println("部门信息添加失败...");
}
第七步:
finally {
//7.关闭连接
if(stmt!= null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
下面写了一个简单的查询数据库的例子,代码如下:
package com.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class Demo{
public static void main(String[] args) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:**数据库名**", "**用户名**", "**密码**");
String sql = "select usid ,uname , pwd ,tel from UserInfo where uname=?and pwd=?";
pstmt = con.prepareStatement(sql);//预编译执行语句
System.out.println("请输入账号:");
String account = sc.nextLine();
System.out.println("请输入密码:");
String pwd = sc.nextLine();
//给预编译执行语句中的占位符赋值
pstmt.setString(1, account);//给预编译语句中的第一个?的赋值
pstmt.setObject(2, pwd);
rs = pstmt.executeQuery();//执行预编译语句
if(rs.next()) {
System.out.println(rs.getObject(1)+"\t"+rs.getObject(2)+"\t"+rs.getObject("pwd")+"\t"+rs.getObject("tel"));
}else {
System.out.println("账号密码错误...");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
这只是简单的查询数据库里面的内容,后面我们可以把查询这些进行封装。虽然后面的学习,我们可以直接用工具,不需要我们手动封装,但自己还是可以选择去试一下,了解一下。