JDBC连接mysql 数据库

复制代码
 1 package cn.edu.njupt.dbconnection;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.PreparedStatement;
 6 import java.sql.ResultSet;
 7 import java.sql.SQLException;
 8 
 9 
10 public class DatabaseConnection {
11 
12 private static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
13 private static final String DBURL = "jdbc:mysql://localhost:3306/jdbcdemo";
14 private static final String DBUSER = "root";
15 private static final String DBPASSWORD = "mysqladmin";
16 private Connection conn;
17 
18 public DatabaseConnection(){
19 try {
20 Class.forName(DBDRIVER);
21 this.conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);
22 } catch (ClassNotFoundException e) {
23 e.printStackTrace();
24 } catch (SQLException e) {
25 e.printStackTrace();
26 }
27 }
28 
29 public Connection getConnection(){
30 return this.conn;
31 }
32 
33 public void close(){
34 if(this.conn != null){
35 try {
36 this.conn.close();
37 } catch (SQLException e) {
38 e.printStackTrace();
39 }
40 }
41 }
42 public static void main(String[] args) {
43 String sql = "create table student(id varchar(5),name varchar(20),primary key(id));";
44 try {
45 PreparedStatement pstmt = new DatabaseConnection().getConnection().prepareStatement(sql);
46 int result = pstmt.executeUpdate();
47 if(result != -1){//创建成功
48 System.out.println("数据库 创建 成功");
49 String sql1 = "insert into student(id,name) values(1,'张三')";
50 int r1 = pstmt.executeUpdate(sql1);
51 System.out.println("数据插入 r1 成功");
52 String sql2 = "insert into student(id,name) values(2,'李四')";
53 int r2 = pstmt.executeUpdate(sql2);
54 System.out.println("数据插入 r2 成功");
55 String sql3 = "select * from student";
56 ResultSet rs = pstmt.executeQuery(sql3);
57 System.out.println("学号\t姓名");
58 while(rs.next()){
59 System.out.println(rs.getString(1)+"\t"+rs.getString(2));
60 }
61 }
62 new DatabaseConnection().close();
63 } catch (SQLException e) {
64 e.printStackTrace();
65 }
66 }
67 
68 }
复制代码

 

posted on   pony1223  阅读(524)  评论(1编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端

导航

< 2012年12月 >
25 26 27 28 29 30 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示