数据库连jdbc基本代码

package lesson13;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class demo {
// Alt+Shift+M封装选择代码块到方法
public static void main(String[] args) {
query();


}

private static void query() {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/lesson14", "root", "888");
st = conn.createStatement();
rs = st.executeQuery("select * from person");
while (rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getString(2));
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(rs != null) {
rs.close();
}
if(st != null) {
st.close();
}
if(conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}


}
}

private static void update() {
Connection conn = null;
Statement st = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/lesson14", "root", "888");
st = conn.createStatement();
int i = st.executeUpdate("update person set name='吴七' where id = 6");
System.out.println("插入成功,影响数据的行数是"+i);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(st != null) {
st.close();
}
if(conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

private static void insert() {
Connection conn = null;
Statement st = null;
try {
// 1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.建立与数据库的连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/lesson14", "root", "888");
// 3.创建提交SQL的对象
st = conn.createStatement();
// 4.提交SQL并处理结果集
int i = st.executeUpdate("insert into person values(null,'赵六')");
System.out.println("插入成功,影响数据的行数是"+i);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
// 5.关闭连接,释放资源
try {
if(st != null) {
st.close();
}
if(conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

posted @   bel_cheng  阅读(87)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示