当前位置:Gxlcms > 数据库问题 > java对MySQL的简单用法

java对MySQL的简单用法

时间:2021-07-01 10:21:17 帮助过:4人阅读

1 String driver = "com.mysql.jdbc.Driver";
2 Class.forName(driver); // classLoader,加载对应驱动

获取连接

String url = "jdbc:mysql://127.0.0.1:3306/webstore?useSSL=false";//服务器IP:127.0.0.1     端口:3306   数据库名:webstore
String username = "root"; //用户名
String password = "123456"; //示例密码
Connection conn = (Connection) DriverManager.getConnection(url, username, password);  //获取连接

执行SQL语句

//向products表插入一条数据
public void add(String id, String pname, String brand, float price, int stock) {
//设计可变SQL语句 String sql
= "insert into product values(‘" + id + "‘,‘" + pname + "‘,‘" + brand + "‘," + price + "," + stock + ")"; try { Statement state = (Statement) conn.createStatement(); // 获取操作声明 if (state.executeUpdate(sql) != 0) { //把SQL语句发送给MySQL运行 System.out.println("插入数据成功!"); } else { System.out.println("插入数据失败!"); } state.close(); } catch (SQLException e) { e.printStackTrace(); }
}
 1     /**
 2      * 显示product表中的所有数据
 3      */
 4     public void selectAll() {
 5         String sql = "select * from product";
 6         try {
 7             Statement statement = (Statement) conn.prepareStatement(sql);
 8             ResultSet res = statement.executeQuery(sql);
 9             System.out.println("产品ID" + "\t" + "产品名称" + "\t" + "品牌" + "\t" + "单价" + "\t" + "库存");
10             while (res.next()) {
11                 System.out.println(res.getString(1) + "\t" + res.getString(2) + "\t" + res.getString(3) + "\t" + res.getFloat(4) +"\t"  + res.getInt(5));
12             }
13             res.close();
14             statement.close();
15         } catch (SQLException e) {
16             e.printStackTrace();
17         }
18     }
19 
20     /**
21      * 通过id显示product表中的数据 
22      * @param id
23      */
24     public void selectById(String id) {
25         String sql = "select * from product where id = " + id;
26         try {
27             Statement statement = (Statement) conn.prepareStatement(sql);  //获取操作声明
28             ResultSet res = statement.executeQuery(sql);   //执行MySQL语句并返回结果集
29             System.out.println("产品ID" + "\t" + "产品名称" + "\t" + "品牌" + "\t" + "单价" + "\t" + "库存");
30             while (res.next()) {  //输出结果集的内容
31 System.out.println(res.getString(1) + "\t" + res.getString(2) + "\t" + res.getString(3) + "\t" + res.getFloat(4) +"\t" + res.getInt(5)); 32 } 33 res.close(); 34 statement.close(); 35 } catch (SQLException e) { 36 e.printStackTrace(); 37 } 38 }

 

java对MySQL的简单用法

标签:val   user   select   数据库名   产品   简单的   插入   int   tco   

人气教程排行