Jdbc需要一个数据库驱动包:mysql-connector-java.jar
然后需要用到的类一般有
Connecto:数据库连接
PrepareStatement(或者Statement):用于执行sql语句
ResultSet:数据库操作返回的结果
以下个人案例:从数据库中查找id = 1的用户信息
1.前期mysql准备
create database cong use cong; create table account( id int primary key auto_increment, name varchar(40), money float )character set utf8 collate utf8_general_ci; insert into account(name,money) values(‘aaa‘,1000); insert into account(name,money) values(‘bbb‘,1000); insert into account(name,money) values(‘ccc‘,1000);
2.创建maven工程,在pom.xml中导入jar包
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cong</groupId> <artifactId>jdbc_learn</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> </dependencies> </project>
3.创建Jdbc_Learn类
import java.sql.*; public class Jdbc_Learn { public static void main(String[] args) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try{ //1.加载数据库驱动 //Class.forName是把这个类加载到JVM中,加载的时候,就会执行其中的静态初始化块,完成驱动的初始化的相关工作。 Class.forName("com.mysql.jdbc.Driver"); //2.通过驱动管理类获得数据库连接a connection = DriverManager.getConnection ("jdbc:mysql://localhost:3306/cong","root","123456"); //3.定义sql语句 String sql = "select * from account where id = ?"; //4.获得预处理statement preparedStatement = connection.prepareStatement(sql); //5.设置参数,第一个参数为 sql 语句中参数的序号(从 1 开始),第二个参数为设置的参数值 preparedStatement.setString(1, "1"); //6.执行操作 resultSet = preparedStatement.executeQuery(); //7.处理结果 while (resultSet.next()){ System.out.println("Account:"+resultSet.getInt("id") + "," + resultSet.getString("name")+ ","+resultSet.getFloat("money")); } }catch (Exception e){ e.printStackTrace(); }finally { //8.释放资源,最先加载的最后释放 if (resultSet != null){ try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (preparedStatement != null){ try { preparedStatement.cancel(); } catch (SQLException e) { e.printStackTrace(); } } if(connection != null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
4.执行,结果如下
参考:https://blog.csdn.net/jungle_rao/article/details/81274720
原文地址:https://www.cnblogs.com/ccoonngg/p/11252112.html
时间: 2024-11-01 03:29:09