javaJDBC增删改查

it2022-05-08  10

import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; public class JdbcDemo { public static void main(String[] args) throws SQLException, ClassNotFoundException{ Statement statement = null;//传递sql语句 //1.加载数据库驱动 Class.forName("com.mysql.jdbc.Driver"); //2.获取数据库的地址,用户名,密码 String url = "jdbc:mysql://localhost:3306/t1"; String username = "root"; String password = "????????";//填写数据库密码 //3.建立一个与数据库的连接 Connection connection = null;//连接对象 connection = (Connection) DriverManager.getConnection(url, username, password); statement = (Statement) connection.createStatement(); addData(statement);//增加数据 // selectData(statement,result);//查询数据 updateData(statement);//修改数据 dropData(statement);//删除数据 //关闭连接 connection.close(); statement.close(); } /** * 查询数据 * @throws SQLException */ public static void selectData(Statement statement) throws SQLException{ String string = "select * from phone"; //4.执行语句 ResultSet result = statement.executeQuery(string); System.out.println("查询最新结果为:"); while(result.next()){ String id1 = result.getString(1); String s1 = result.getString(2); String s2 = result.getString(3); String s3 = result.getString(4); String s4 = result.getString(5); System.out.println("id = "+id1+" name = "+s1+" 价格= "+s2+" 上市时间= "+s3+" 公司= "+s4); System.out.println("\t"); } } /** * 删除数据 * @throws SQLException */ public static void dropData(Statement statement) throws SQLException{ String string = "delete ignore from phone where id=2"; //执行语句 @SuppressWarnings("unused") Boolean result = statement.execute(string); System.out.println("删除指定数据后的表为:"); selectData(statement); } /** * 修改数据 * @throws SQLException */ public static void updateData(Statement statement) throws SQLException{ String string = "update ignore phone set name = '未知' where id=1"; //执行语句 @SuppressWarnings("unused") Boolean result = statement.execute(string); System.out.println("修改指定数据后的表为:"); selectData(statement); } /** * 增加数据 * @throws SQLException */ public static void addData(Statement statement) throws SQLException{ String string = "insert ignore into phone(id,name,price,上市时间,company) values(8,'诺基亚',3600,'2012-5-9','诺基亚')"; //执行语句 @SuppressWarnings("unused") Boolean result = statement.execute(string); System.out.println("增加指定数据后的表为:"); selectData(statement); } }

分四步:

1.加载数据库驱动

       Class.forName("com.jdbc.mysql.Driver";

2.获取数据库url,用户名,密码

3.建立数据库连接

      Connection conn = DriverManager.getConnection(url,username,password);

      Statement statement = coon.createStatement();

4.执行语句

      ResultSet res = statement.executeQuery("sql语句")//适用于查询

      或者 Boolean res = statement.execute("sql语句");//适用于增删改

               后使用res.next()进行迭代输出;

5.关闭连接


最新回复(0)