我的第一个JDBC连接测试
package com.lich.sample.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Demo { public static void main(String[] args) throws SQLException { String url = "jdbc:mysql://localhost:3306/jdbc"; String username = "root"; String password = "root"; //1.加载驱动 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //2.获取与数据库的链接 Connection conn = DriverManager.getConnection(url, username, password); //3.获取用于向数据库发送sql语句的statement Statement st = conn.createStatement(); //4.向数据库发sql,并获取代表结果集的resultset String sql = "select id,name,password,email,birthday from user"; ResultSet rs = st.executeQuery(sql); //5.取出结果集的数据 while(rs.next()){ System.out.println("id=" + rs.getObject("id")); System.out.println("name=" + rs.getObject("name")); System.out.println("password=" + rs.getObject("password")); System.out.println("email=" + rs.getObject("email")); System.out.println("birthday=" + rs.getObject("birthday")); } //6.关闭链接,释放资源 rs.close(); st.close(); conn.close(); } }
User.sql脚本文件
create database jdbc character set utf8 collate utf8_general_ci; use jdbc; create table user( id int primary key auto_increment, name varchar(40), password varchar(40), email varchar(60), birthday date )character set utf8 collate utf8_general_ci; insert into user(name,password,email,birthday) values('zs','123456','zs@sina.com','1980-12-04'); insert into user(name,password,email,birthday) values('lisi','123456','lisi@sina.com','1981-12-04'); insert into user(name,password,email,birthday) values('wangwu','123456','wangwu@sina.com','1979-12-04');