JDBC使用步骤
//注册驱动,加载驱动 Class.forName("com.mysql.jdbc.Driver"); //创建连接(你要对哪一个数据库进行操作) String url="jdbc:mysql://localhost:3306/test"; //连接数据库,用户认证 Connection conn = DriverManager.getConnection(url,"root","913816"); //编写sql语句 String sql=""; //创建执行对象 PreparedStatement ps = conn.prepareStatement(sql); //执行sql语句 int i = ps.executeUpdate();// int类型的值,就是返回的记录数 //释放资源 if(conn!=null) { conn.close(); } if(ps!=null) { ps.close(); }
//注册驱动,加载驱动
Class.forName("com.mysql.jdbc.Driver");
//创建连接(你要对哪一个数据库进行操作)
String url="jdbc:mysql://localhost:3306/test";
//连接数据库,用户认证
Connection conn = DriverManager.getConnection(url,"root","913816");
//编写sql语句
String sql="";
//创建执行对象
PreparedStatement ps = conn.prepareStatement(sql);
//执行sql语句
int i = ps.executeUpdate();// int类型的值,就是返回的记录数
//释放资源
if(conn!=null) {
conn.close();
}
if(ps!=null) {
ps.close();
}
JDBC工具类编写(增删改为例)
utils包JDBCUtils类中
package utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCUtil { //test为服务器名字
public static final String URL = "jdbc:mysql://localhost/test"; // 只限在本地数据库连接
public static final String DRIVER = "com.mysql.jdbc.Driver";
// 返回一个可以使用的链接
public static Connection getCollection(){
Connection conn = null;
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL,"root","root");
//第一个root为数据库用户名,第二个root为密码
} catch (Exception e) {
System.out.println("获取链接失败");
e.printStackTrace();
}
return conn;
}
// 释放资源
public static void close(PreparedStatement pstmt, Connection connection){
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
jdec包JdbcTest主类中
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
import com.mysql.jdbc.Statement;
import utils.JDBCUtil;
public class JdbcTest {
public static void main(String[] args) throws Exception {
up();
}
public static void up() throws Exception {
Connection conn = JDBCUtil.getCollection();
String sql = "update dept set dlocation = '南京' where deptno=10";
PreparedStatement pstmt = conn.prepareStatement(sql);
int i = pstmt.executeUpdate();// int类型的值,就是返回的记录数
System.out.println(i);
JDBCUtil.close(pstmt,conn);
}
}