JDBC连接数据库代码

时间:2021-12-28 03:29:14
//连接是需要导包   http://pan.baidu.com/s/1o6nyuOa 
/*配合数据库建立表

create database day14 character set utf8 collate utf8_general_ci;

use day14;

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,'zs','123456','zs@sina.com','1980-12-04');
insert into users(id,name,password,email,birthday) values

(2,'lisi','123456','lisi@sina.com','1981-12-04');
insert into users(id,name,password,email,birthday) values

(3,'wangwu','123456','wangwu@sina.com','1979-12-04');

*/
package cn.itcast.demo; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement; public class Demo1 {
public static void main(String[] args) throws Exception { String url="jdbc:mysql://localhost:3306/day14";
String username="root";
String password="seeker"; //1.加载驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //2.获取与数据库的连接,导接口包,程序的维护性好,
Connection conn = DriverManager.getConnection(url, username, password); //3.获得发送语句的statement对象
Statement st=conn.createStatement(); //4.向数据库发送sql,并获得结果集(表格方式封装)
String sql="select id,name,password,email,birthday from users";
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();
}
}