package mysql_3;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author 小虎牙
*
*/
public class mysql_2020_10_09 {
@SuppressWarnings("resource")
public static void main(String[] args) {
Connection con=null;
Statement s=null;
ResultSet rs=null;
// TODO 自动生成的方法存根
try {
//第一步注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
String URL = "jdbc:mysql://localhost:3306/java?serverTimezone=UTC&characterEncoding=utf-8"; // 连接MySQL数据库的路径
// 第二步建立连接
con = DriverManager.getConnection(URL, "root", "root");
// 第三步建立发送sql的类(不带参数的简单sql的语句)
s = con.createStatement();
// 第四部接受sql的结果集
rs = s.executeQuery("select *from user ");
while (rs.next()) {
System.out.print(rs.getString(1) + "\t");
System.out.print(rs.getString(2) + "\t");
System.out.println(rs.getString(3) + "\t");
}
//第三步的第2种带参数的sql,使用通配符动态的执行sql语句(使用通配符相对安全一些)
//PreparedStatement他继承了Statement
PreparedStatement ps=con.prepareStatement("select *from user where name=?");
ps.setString(1, "张三");
System.out.println("---------------------------");
rs = ps.executeQuery();
while (rs.next()) {
System.out.print(rs.getString(1) + "\t");
System.out.print(rs.getString(2) + "\t");
System.out.println(rs.getString(3) + "\t");
}
} catch (ClassNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
if (s != null) {
try {
s.close();
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
}
java-数据库-3
猜你喜欢
转载自blog.csdn.net/huiguo_/article/details/108981332
今日推荐
周排行