java对MySQL的简单用法

java对MySQL操作说白了就是三步:加载驱动—>获取连接—>执行SQL语句—>显示结果
这里我想说一下的是执行SQL语句的操作,书写SQL语句时一定要注意与本来的SQL语句完全一致,就是说SQL中的字符串是有一对单引号引起来的,到你写在java时也要加上一对单引号,当然执行还有别的方法,这里只说一种,下面是一些简单的例子:

加载对应驱动

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 }

猜你喜欢

转载自www.cnblogs.com/li1234567980/p/11104830.html