MySQL JDBC简单使用
Posted Mr. Tan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL JDBC简单使用相关的知识,希望对你有一定的参考价值。
首先需要去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简单使用的主要内容,如果未能解决你的问题,请参考以下文章
mysql jdbc源码分析片段 和 Tomcat's JDBC Pool