JDBC练习
第一步:建表
CREATE table users(
id INT PRIMARY KEY,
name VARCHAR(40),
password VARCHAR(40),
email VARCHAR(60),
birthday DATE
);
第二步:插入数据:
INSERT into users(id,name,PASSWORD,email,birthday)VALUES (1,'zhangsan','123456','zs@bindu.com','1992-12-04');
INSERT into users(id,name,PASSWORD,email,birthday)VALUES (2,'lisi','123456','ls@bindu.com','1995-11-14');
INSERT into users(id,name,PASSWORD,email,birthday)VALUES (3,'wangwu','123456','ww@bindu.com','1993-2-04');
观察结果:
第三步:
package me.gacl.demo; 2 import java.sql.Connection; 3 import java.sql.DriverManager; 4 import java.sql.ResultSet; 5 import java.sql.Statement; 6 7 public class JdbcFirstDemo { 8 9 public static void main(String[] args) throws Exception { 10 //要连接的数据库URL 11 String url = "jdbc:mysql://localhost:3306/jdbcStudy"; 12 //连接的数据库时使用的用户名 13 String username = "root"; 14 //连接的数据库时使用的密码 15 String password = "XDP"; 16 17 //1.加载驱动 18 //DriverManager.registerDriver(new com.mysql.jdbc.Driver());不推荐使用这种方式来加载驱动 19 Class.forName("com.mysql.jdbc.Driver");//推荐使用这种方式来加载驱动 20 //2.获取与数据库的链接 21 Connection conn = DriverManager.getConnection(url, username, password); 22 23 //3.获取用于向数据库发送sql语句的statement 24 Statement st = conn.createStatement(); 25 26 String sql = "select id,name,password,email,birthday from users"; 27 //4.向数据库发sql,并获取代表结果集的resultset 28 ResultSet rs = st.executeQuery(sql); 29 30 //5.取出结果集的数据 31 while(rs.next()){ 32 System.out.println("id=" + rs.getObject("id")); 33 System.out.println("name=" + rs.getObject("name")); 34 System.out.println("password=" + rs.getObject("password")); 35 System.out.println("email=" + rs.getObject("email")); 36 System.out.println("birthday=" + rs.getObject("birthday")); 37 } 38 39 //6.关闭链接,释放资源 40 rs.close(); 41 st.close(); 42 conn.close(); 43 } 44 }