连接数据库进行数据操作

首先引入mysql驱动jar包

mysql-connector-java-5.1.27.jar


直接上代码


public class User {
private String id ;
private String username ;
private String password;
private String subgroup;

public User() {
super();
}

public User(String id, String username, String password, String subgroup) {
super();
this.id = id;
this.username = username;
this.password = password;
this.subgroup = subgroup;
}
}


public class ConnectionTest01 {
public static void main(String[] args) {
//声明Connection对象
Connection con;
//驱动程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名mydata
String url = "jdbc:mysql://localhost:3306/a3test";
//MySQL配置时的用户名
String user = "root";
//MySQL配置时的密码
String password = "chao0321o";
//遍历查询结果集
try {
//加载驱动程序
Class.forName(driver);
//1.getConnection()方法,连接MySQL数据库!!
con = DriverManager.getConnection(url,user,password);
if(!con.isClosed()){
System.out.println("Succeeded connecting to the Database!");
}
Statement statement = con.createStatement();
//要执行的SQL语句
String sql = "select * from user";
//3.ResultSet类,用来存放获取的结果集!!
ResultSet rs = statement.executeQuery(sql);

String username = "";
String id = "";
String password1 = "";
while(rs.next()){
//获取stuname这列数据
id = rs.getString("id");
//获取stuid这列数据
username = rs.getString("username");
password1 = rs.getString("password");

//输出结果
System.out.println(id + "\t" + username + "\t" + password1);
}
rs.close();
con.close();

} catch (Exception e) {

}


}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值