码迷,mamicode.com
首页 > 数据库 > 详细

MySQL JDBC简单使用

时间:2018-11-03 19:15:02      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:creat   ssl   rest   cal   val   time   col   exception   user   

首先需要去MySQL官网下载MySQL JDBC驱动

导入jar包

 1 String driver = "com.mysql.jdbc.Driver";
 2 String url = "jdbc:mysql://localhost:3306/yourTable";
 3 String username = "root";
 4 String password = "";
 5 Connection connection = null;
 6 try {
 7     Class.forName(driver);  // ClassLoader加载对应驱动
 8     connection = DriverManager.getConnection(url, username, password);
 9 } catch (ClassNotFoundException e) {
10     e.printStackTrace();
11 } catch (SQLException e) {
12     e.printStackTrace();
13 }
14 /**
15  * 创建表
16  */
17 String sql = "create table nihao(name varchar(10) primary key, password varchar(10), nowtime date, age int)";
18 PreparedStatement ps = null;
19 try {
20     ps = connection.prepareStatement(sql);
21     ps.executeUpdate();
22     ps.close();
23 } catch (SQLException e) {
24     e.printStackTrace();
25 }
26 /**
27  * 插入数据
28  */
29 sql = "insert into nihao(name, password, nowtime, age) values (?, ?, ?, ?)";
30 try {
31     ps = connection.prepareStatement(sql);
32     ps.setString(1, "root");
33     ps.setString(2, "sqdw");
34     ps.setDate(3, new java.sql.Date(new Date().getTime()));
35     ps.setInt(4, 19);
36     int i = ps.executeUpdate();
37     System.out.println(i);
38     ps.close();
39 } catch (SQLException e) {
40     e.printStackTrace();
41 }
42 /**
43  * 查询数据
44  */
45 sql = "select name, password, nowtime, age from nihao";
46 try {
47     ps = connection.prepareStatement(sql);
48     ResultSet rs = ps.executeQuery();
49     while (rs.next())
50         System.out.print("姓名是: " + rs.getString("name") + ", 密码是:" + rs.getString("password") +
51                 ". 日期是: " + rs.getDate("nowtime") + ", 年龄是:" + rs.getInt("age"));
52     ps.close();
53 } catch (SQLException e) {
54     e.printStackTrace();
55 }
56 try {
57     connection.close();
58 } catch (SQLException e) {
59     e.printStackTrace();
60 }

删除也用executeUpdate()即可。

MySQL JDBC简单使用

标签:creat   ssl   rest   cal   val   time   col   exception   user   

原文地址:https://www.cnblogs.com/sqdtss/p/9901547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!