实现的基本步骤:
1、加载驱动程序:
Class.forName("com.mysql.jdbc.Driver");
2、获得数据可连接:
private static final String url = "jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=UTF-8&useSSL=false"; //数据库地址 private static final String usename = "root"; private static final String password = "root"; //数据库密码 Connection connection = DriverManager.getConnection(URL,USER,PASSWORD);
其中,url中jdbc表示连接方式,mysql表示数据库软件为mysql,localhost表示数据库地址,3306表示数据库端口,shopping表示数据库名称。
3、通过数据库的连接操作数据库,实现增删改查
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM goods;"); //用于执行数据库查询
ResultSet resultSet = statement.executeUpdate("");//用于执行数据库更新
另外一种sql语句执行方法:
PreparedStatement pStatement = connection.prepareStatement(""); //编译sql代码 pStatement.execute(); //执行sql代码
下面是一个完整的测试代码:
package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBHelper { private static String driver = "com.mysql.jdbc.Driver"; //数据库驱动 //连接数据库的URL地址 private static final String url = "jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=UTF-8&useSSL=false"; private static final String usename = "root"; private static final String password = "root"; //数据库密码 private static Connection connection =null; //静态代码块负责加载驱动 static{//静态块中的代码会优先被执行 try { Class.forName(driver); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //单例模式返回数据库连接对象 public static Connection getConnection(){ if(connection==null){ try { connection = DriverManager.getConnection(url,usename,password); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return connection; } return connection; } public static void main(String[] args) { ResultSet resultSet = null; try{ Connection connection = DBHelper.getConnection(); Statement statement = connection.createStatement(); resultSet = statement.executeQuery("SELECT * FROM goods;"); while(resultSet.next()){ System.out.println(resultSet.getString("name")); } }catch(Exception e){ e.printStackTrace(); } } }
时间: 2024-12-11 14:17:16