jdbc快速连接mysql数据库,使用JAVA jdbc编写一段快速连接Mysql数据库

使用JAVA jdbc编写一段快速连接Mysql数据库

第一次写文档,看的人轻喷。做一个简单记录

话不多说,下面直接上代码。

public static void main(String[] args) {

Connection conn = null;

String sql;

// String url = "jdbc:mysql://localhost:3306/test?" +

// "user=root&password=root&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT";

String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT";

String user = "root";

String password = "root";

try {

Class.forName("com.mysql.jdbc.Driver");

log.info("成功加载MySql驱动程序");

conn = DriverManager.getConnection(url, user, password);

Statement stmt = conn.createStatement();

sql = "create table student(No char(30), name varchar(30), primary key(No))";

int result = stmt.executeUpdate(sql);

if (result != -1) {

log.info("创建数据表成功");

sql = "insert into student(no, name) values ('201901', 'sui123')";

result = stmt.executeUpdate(sql);

sql = "insert into student(no, name) values ('201902', 'ya123')";

result = stmt.executeUpdate(sql);

sql = "select * from student";

ResultSet rs = stmt.executeQuery(sql);

while (rs.next()) {

log.info(rs.getString(1) + "\t" + rs.getString(2));

}

}

} catch (ClassNotFoundException e) {

log.error("没有找到驱动类");

throw new RuntimeException("没有找到加载类");

} catch (SQLException e) {

log.error("sql不正确", e.getMessage(), e);

throw new RuntimeException("sql不正确");

} finally {

try {

conn.close();

} catch (SQLException e) {

log.error("关闭连接失败");

throw new RuntimeException("关闭连接失败");

}

}

}

这样

标签:jdbc,JAVA,log,Mysql,stmt,result,sql,String

来源: https://blog.csdn.net/suifengyangerqu/article/details/88767263

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值