package com.kuang.testJDBC;
import java.sql.*;
public class TestJDBC {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//useUnicode=true&characterEncoding=utf-8解决中文乱码问题
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username="root";
String password="2001";
//1.加载驱动
//通过反射,调用类加载器实现驱动加载,实际上是调用DriverManager来实现注册一个Driver对象进行连接的。
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,获得连接对象
Connection connection = DriverManager.getConnection(url, username, password);
//3.获得向数据库发送SQL的对象statement:CRUD
Statement statement = connection.createStatement();
//4.编写SQL
String sql="select * from people";
//5.执行查询,并将结果返回给结果集
ResultSet resultSet = statement.executeQuery(sql);
//如果resultSet结果集还有下一条数据,就依次遍历输出
while (resultSet.next()){
System.out.println("id:"+resultSet.getObject("id"));
System.out.println("name:"+resultSet.getObject("name"));
System.out.println("age:"+resultSet.getObject("age"));
System.out.println("address:"+resultSet.getObject("address"));
System.out.println("==============================================");
}
//关闭连接,先打开的后关闭
resultSet.close();
statement.close();
connection.close();
}
}
预编译
package com.kuang.testJDBC;
import java.sql.*;
public class PrepareStatementTest {
public static void main(String[] args) throws Exception {
//配置信息
//useUnicode=true&characterEncoding=utf-8解决中文乱码问题
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username="root";
String password="2001";
//1.加载驱动
//通过反射,调用类加载器实现驱动加载,实际上是调用DriverManager来实现注册一个Driver对象进行连接的。
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,获得连接对象
Connection connection = DriverManager.getConnection(url, username, password);
//4.编写SQL
String sql="insert into people(id,`name`,`age`,`address`) values (?,?,?,?)";
//3.获得向数据库发送SQL的对象statement:CRUD
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,7);
preparedStatement.setString(2,"鸡哥");
preparedStatement.setString(3,"6");
preparedStatement.setString(4,"广西");
//5.执行
int i = preparedStatement.executeUpdate();
if (i>0){
System.out.println("添加成功");
}
//关闭连接,先打开的后关闭
preparedStatement.close();
connection.close();
}
}