这个示例是Java操作MySql的基本方法。
在这个示例之前,要安装好MySql,并且配置好账户密码,创建一个logininfo数据库,在数据库中创建userinfo数据表。并且在表中添加示例数据。
一、首先将mysql-connector-java-5.1.26-bin.jar开发包复制到lib文件夹中,并且Build Path->Add Build Path。
二、创建User类,用于封装从数据库读出来的数据。
1 package com.mylx.database; 2 3 public class User { 4String id; 5String username; 6String password; 7 8public String getId() { 9 return id;10}11 12public void setId(String id) {13 this.id = id;14}15 16public String getUsername() {17 return username;18}19 20public void setUsername(String username) {21 this.username = username;22}23 24public String getPassword() {25 return password;26}27 28public void setPassword(String password) {29 this.password = password;30}31 }
查看源码
三、创建测试类MyDatabaseMySQL,在主函数中添加连接数据库、执行查询、封装数据和遍历数据集合的代码。
1 package com.mylx.database; 2 //Java使用Jdbc操作MySql数据库(一) 3 4 import java.sql.Connection; 5 import java.sql.DriverManager; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 import java.sql.Statement; 9 import java.util.ArrayList;10 import java.util.List;11 12 public class MyDatabaseMySQL {13 14public static void main(String[] args) {15 String driverStr = "com.mysql.jdbc.Driver";16 String dataUrlStr = "jdbc:mysql://192.168.2.100:3306/logininfo";17 String nameStr = "root";18 String passwordStr = "admin";19 String sqlStr = "select * from userinfo";20 Connection conn = null;21 Statement stat = null;22 List<User> usersList = new ArrayList<User>();23 24 try {25 //先将mysql-connector-java-5.1.26-bin.jar开发包复制到lib文件夹中26 //并且Build Path->Add Build Path27 //加载驱动类28 Class.forName(driverStr);29 //创建数据连接30 conn = DriverManager.getConnection(dataUrlStr, nameStr, passwordStr);31 //获得查询数据记录集32 stat = conn.createStatement();33 ResultSet rs = stat.executeQuery(sqlStr);34 //遍历记录集,并将各字段数据读取封装到数据集合当中35 for (rs.first(); !rs.isAfterLast(); rs.next()) {36 User tmpUser = new User();37 tmpUser.setId(rs.getString(1));38 tmpUser.setUsername(rs.getString(2));39 tmpUser.setPassword(rs.getString(3));40 usersList.add(tmpUser);41 }42 } catch (Exception e) {43 e.printStackTrace();44 } finally {45 if (conn != null) {46 try {47 //关闭连接48 conn.close();49 } catch (SQLException e) {50 e.printStackTrace();51 }52 }53 }54 //遍历数据集合并打印输出55 if (usersList != null) {56 for (int i = 0; i < usersList.size(); i++) {57 System.out.print(usersList.get(i).getId() + "-->");58 System.out.print(usersList.get(i).getUsername() + "-->");59 System.out.print(usersList.get(i).getPassword() + "\n");60 }61 }62}63 }
查看源码
运行结果: