连接数据库操作步骤如下
- 架包 jar
- 建表
- 源码解析
1:架包 jar
根据自己本版本选择正确jar包,本例采用maven 管理局,在pom.xml 中添加如下代码,自动下载架包
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.25</version> </dependency>
2:建表
DROP TABLE IF EXISTS `tb_user`; CREATE TABLE `tb_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(20) DEFAULT NULL, `password` varchar(20) DEFAULT NULL, `head_root` varchar(80) DEFAULT NULL, `realname` varchar(10) DEFAULT NULL, `netname` varchar(20) DEFAULT NULL, `email` varchar(20) DEFAULT NULL, `age` int(10) DEFAULT NULL, `sex` varchar(2) DEFAULT NULL, `birth_year` int(10) DEFAULT NULL, `birth_month` int(10) DEFAULT NULL, `birth_day` int(10) DEFAULT NULL, `addressid` int(11) DEFAULT NULL COMMENT '地址详细信息', `tall` double(11,0) DEFAULT NULL, `user_grade` varchar(10) DEFAULT NULL, `income` double(20,0) DEFAULT NULL, `marry` varchar(5) DEFAULT NULL, `marrySex` varchar(2) DEFAULT NULL, `gexingmsg` varchar(80) DEFAULT NULL, `vip` int(10) DEFAULT NULL, `money` int(11) DEFAULT NULL, `renzheng` varchar(10) DEFAULT NULL, `fenlei` varchar(10) DEFAULT NULL, `biaoqian` int(11) DEFAULT NULL, `user_black` int(11) DEFAULT NULL, `user_youhui` int(11) DEFAULT NULL, `user_work` varchar(10) DEFAULT NULL, `user_home` int(11) DEFAULT NULL, `user_car` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;
3:源码
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * @author Evan * */ public class JDBCTest { public static void main(String[] args) throws Exception { Connection connection = null; PreparedStatement prepareStatement = null; ResultSet rs = null; try { // 加载驱动 Class.forName("com.mysql.jdbc.Driver"); // 获取连接 String url = "jdbc:mysql://127.0.0.1:3306/test"; String user = "root"; String password = "asplover"; connection = DriverManager.getConnection(url, user, password); // 获取statement,preparedStatement String sql = "select * from tb_user where id=?"; prepareStatement = connection.prepareStatement(sql); // 设置参数 prepareStatement.setLong(1, 1); // 执行查询 rs = prepareStatement.executeQuery(); // 处理结果集 while (rs.next()) { System.out.println("用户名:"+rs.getString("userName")); System.out.println("密码为:"+rs.getString("password")); } } finally { // 关闭连接,释放资源 if (rs != null) { rs.close(); } if (prepareStatement != null) { prepareStatement.close(); } if (connection != null) { connection.close(); } } } }