当前位置:网站首页>JDBC Codes connexes
JDBC Codes connexes
2022-06-29 18:13:00 【Seigneur, pécheur.】
Un.、statementMise en œuvresqlDéclarations()
(1)Classe d'outils
package Zer.demo.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
public static String driver;
public static String url;
public static String root;
public static String password;
static {
try {
//Lire les ressources,Profil
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
//Instanciate Profile Object get resources
Properties properties = new Properties();
//Pour charger les ressources lues
properties.load(in);
// Lire la ressource pour la stocker
driver = properties.getProperty("driver");
url = properties.getProperty("url");
root = properties.getProperty("root");
password = properties.getProperty("password");
//1.Charger l'entraînement
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
//2.Obtenir la connexion
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, root, password);
}
//3.Libérer des ressources
public static void rslease(Connection coon, Statement st, ResultSet resultSet){
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (st!=null){
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (coon!=null){
try {
coon.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
(2)Profil
Nom:db.Properties,Moi - même.newCréer un nouveau, Icône comme ci - dessous
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai
root=root
password=123456
1.Supprimer
package Zer.demo.Caozuo;
import Zer.demo.util.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Delete {
public static void main(String[] args) {
Connection coon = null;
Statement st = null;
ResultSet resultSet = null;
try {
//Cette méthode a été appelée, Le bloc de code statique s'exécute automatiquement . Le pilote de chargement a été exécuté
coon = JdbcUtils.getConnection();
st = coon.createStatement();
String sql ="delete from grade where gradeid=25";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("Suppression réussie");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtils.rslease(coon,st,resultSet);
}
}
}
2.Mise à jour
package Zer.demo.Caozuo;
import Zer.demo.util.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Update {
public static void main(String[] args) {
Connection coon = null;
Statement st = null;
ResultSet resultSet = null;
try {
//Cette méthode a été appelée, Le bloc de code statique s'exécute automatiquement . Le pilote de chargement a été exécuté
coon = JdbcUtils.getConnection();
st = coon.createStatement();
String sql ="update grade set gradename='Tout le monde est pareil., Même si c'est différent , Ça ne fait pas de mal d'être fatigué ' where gradeid= 22";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("Mise à jour réussie");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtils.rslease(coon,st,resultSet);
}
}
}
3.Insérer
package Zer.demo.Caozuo;
import Zer.demo.util.JdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Insert {
public static void main(String[] args) {
Connection coon = null;
Statement st = null;
ResultSet resultSet = null;
try {
//Cette méthode a été appelée, Le bloc de code statique s'exécute automatiquement . Le pilote de chargement a été exécuté
coon = JdbcUtils.getConnection();
st = coon.createStatement();
String sql ="insert into grade values(25,' Il n'y a pas de perte supplémentaire à marcher ')";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("Insertion réussie");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtils.rslease(coon,st,resultSet);
}
}
}
4.Requête
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Select {
public static void main(String[] args) {
Connection coon = null;
Statement st = null;
ResultSet resultSet = null;
try {
//Cette méthode a été appelée, Le bloc de code statique s'exécute automatiquement . Le pilote de chargement a été exécuté
coon = JdbcUtils.getConnection();
st = coon.createStatement();
String sql= "SELECT * FROM grade";
//5、Avec lestatementExécution de l'objetsqlDéclarations,Renvoie l'ensemble de résultats
resultSet = st.executeQuery(sql);
while (resultSet.next()){
System.out.println("gradeid="+resultSet.getObject("gradeid"));
System.out.println("gradename="+resultSet.getObject("gradename"));
System.out.println("………………………………………………………………………………………………………………………………………");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtils.rslease(coon,st,resultSet);
}
}
}
Si elle est utiliséestatement Bien qu'il soit facile de comprendre ,Mais il y aSQLProblèmes d’injection,Risque potentiel pour la sécurité, Recommandé à cette fin preparestatement
5、SQLProblèmes d’injection
stamentExisteSQLProblèmes d’injection
package Zer.demo.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class Zhuru {
public static void main(String[] args) {
Login(14," 'or '1=1");
}
// Énoncé d'entreprise
public static void Login(int password11,String yonghuming){
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
st= conn.createStatement();
String sql = "select * from grade where gradeid ='"+password11+"' and gradename='"+yonghuming+"'";
rs = st.executeQuery(sql);
while (rs.next()){
System.out.println(rs.getString("gradename"));
System.out.println(rs.getInt("gradeid"));
}
} catch (Exception throwables) {
throwables.printStackTrace();
}finally {
JdbcUtils.rslease(conn,st,rs);
}
}
}
2.、PreparedstatementMise en œuvresqlDéclarations
(1)Classe d'outils
package Zer.demo.util;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils1 {
public static String driver = null;
public static String url = null;
public static String root = null;
public static String password = null;
static {
try {
InputStream in = JdbcUtils1.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
root = properties.getProperty("root");
password = properties.getProperty("password");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getconnection() throws SQLException {
return DriverManager.getConnection(url,root,password);
}
public static void release(Connection conn, PreparedStatement pr, ResultSet rs){
if (rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (pr!=null){
try {
pr.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
(2)Profil
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai
root=root
password=123456
1、Supprimer
package Zer.demo.PrepareStatement;
import Zer.demo.util.JdbcUtils1;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Delete1 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils1.getconnection();
String sql = "delete from grade where gradeid = ?";//Écris d'abord.SQLDéclarations,‘?’C'est un symbole d'occupation
ps = conn.prepareStatement(sql);//Précompilé,Ne pas exécuter
//Exécution manuelleSQLDéclarations
ps.setInt(1, 26);
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("Suppression réussie");
} else {
System.out.println("Échec de la suppression");
}
} catch (Exception throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils1.release(conn, ps, rs);
}
}
}
## 2、Mise à jour
package Zer.demo.PrepareStatement;
import Zer.demo.util.JdbcUtils1;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Update1 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils1.getconnection();
String sql = "update grade set gradename = ? where gradeid = ?";//Écris d'abord.SQLDéclarations,‘?’C'est un symbole d'occupation
ps = conn.prepareStatement(sql);//Précompilé,Ne pas exécuter
//Exécution manuelleSQLDéclarations
ps.setString(1, " La voie des femmes , Apprendre à prendre soin de soi ");
ps.setInt(2, 26);
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("Mise à jour réussie");
} else {
System.out.println("Échec de la mise à jour");
}
} catch (Exception throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils1.release(conn, ps, rs);
}
}
}
3、Insérer
package Zer.demo.PrepareStatement;
import Zer.demo.util.JdbcUtils1;
import java.sql.*;
public class Insert1 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils1.getconnection();
String sql = "insert into grade(gradeid,gradename) values(?,?)";//Écris d'abord.SQLDéclarations,‘?’C'est un symbole d'occupation
ps = conn.prepareStatement(sql);//Précompilé,Ne pas exécuter
//Exécution manuelleSQLDéclarations
ps.setInt(1, 26);//Premier substituant,Affectation26
ps.setString(2, "La voie du gentleman,Auto - culture");//Deuxième substituant, La façon d'assigner un gentleman ,Auto - culture
int i = ps.executeUpdate();
if (i > 0) {
System.out.println("Insertion réussie");
} else {
System.out.println("L'insertion a échoué");
}
} catch (Exception throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils1.release(conn, ps, rs);
}
}
}
4、Requête
package Zer.demo.PrepareStatement;
import Zer.demo.util.JdbcUtils1;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Select1 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils1.getconnection();
String sql = "select * from grade";
String sql1 = "select * from grade";
ps = conn.prepareStatement(sql);//Précompilé,Ne pas exécuter
//Exécution manuelleSQLDéclarations, Il n'y a pas de place pour ne pas écrire
rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt("gradeid"));
System.out.println(rs.getString("gradename"));
}
} catch (Exception throwables) {
throwables.printStackTrace();
} finally {
JdbcUtils1.release(conn, ps, rs);
}
}
}
边栏推荐
- 牛客小Bai月赛52 D 环上食虫(尺取+st表)
- Prevent form resubmission based on annotations and interceptors
- Partial mock of static class of phpunit operation
- Web Scraping with Beautiful Soup for Data Scientist
- lodash深拷贝使用
- [tcapulusdb knowledge base] tcapulusdb doc acceptance - Introduction to creating game area
- Serial port experiment based on stm32f103zet6 library function
- Configure the local domain name through the hosts file
- C comparison of the performance of dapper efcore sqlsugar FreeSQL hisql sqlserver, an ORM framework at home and abroad
- MaxCompute字符串替换函数-replace
猜你喜欢
Image migration and data migration synchronization of old and new servers with different Alibaba cloud accounts
Adobe Premiere基础-批量素材导入序列-变速和倒放(回忆)-连续动作镜头切换-字幕要求(十三)
Abc253 D fizzbuzz sum hard (tolerance exclusion theorem)
Adobe Premiere基础-时间重映射(十)
Adobe Premiere基础-编辑素材文件常规操作(脱机文件,替换素材,素材标签和编组,素材启用,便捷调节不透明度,项目打包)(十七)
Request header field xxxx is not allowed by Access-Control-Allow-Headers in preflight response问题
Visio annotation, annotation location
Proxmox VE Install 7.2
小白月赛51 补题 E G F
Adobe Premiere基礎-聲音調整(音量矯正,降噪,電話音,音高換擋器,參數均衡器)(十八)
随机推荐
On adding and subtracting dates
Find the maximum XOR value in the sequence given a number (01 Dictionary)
Adobe Premiere基础-编辑素材文件常规操作(脱机文件,替换素材,素材标签和编组,素材启用,便捷调节不透明度,项目打包)(十七)
Force deduction daily question 06.29 add two numbers
Image migration and data migration synchronization of old and new servers with different Alibaba cloud accounts
Detailed introduction and Simulation of bitmap
Prevent form resubmission based on annotations and interceptors
给定一个数在序列中求最大异或值(01字典)
【目标跟踪】|stark配置 win otb
通过 hosts文件配置本地域名
Goldfish rhca memoirs: do447 building advanced job workflow -- using fact cache to improve performance
第42期:MySQL 是否有必要多列分区
When easycvr deploys a server cluster, what is the reason why one is online and the other is offline?
Analyze the implementation principle of zero copy mechanism, applicable scenarios and code implementation
mysql — 清空表中数据
【TcaplusDB知识库】TcaplusDB单据受理-事务执行介绍
国内酒店交易DDD应用与实践——理论篇
What technology is an applet container? Can it help Internet of things enterprises break through the red sea?
3H proficient in opencv (VIII) - shape detection
Maximum length of palindrome substring (string hash + binary)