JDBC连接数据库
-
导入jar包
mysql-connector-java-5.1.47.jar
-
加载驱动
Class.forName(“com.mysql.jdbc.Driver”);
-
用户信息和url
String url = “jdbc:mysql://localhost:3306/wsddd?”;
String name = “root”;
String pwd = “Wsd246503”; -
连接成功,数据库对象,connection代表数据库
Connection connection = DriverManager.getConnection(url, name, pwd);
-
执行SQL的对象 statment 执行SQL的对象
Statement statement = connection.createStatement();
-
执行SQL对象去执行SQL,可能存在结果,返回查看结果
String sql = “SELECT * FROM orders”;
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.println("order_num "+ resultSet.getObject(“order_num”));
System.out.println("order_date "+ resultSet.getObject(“order_date”));
System.out.println(“order_date “+ resultSet.getObject(“order_date”));
System.out.println(”=====”);
} -
释放资源
resultSet.close();
statement.close();
connection.close(); -
完整代码
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class JdbcDemo1 { public static void main(String[] args) throws Exception { //1.加载驱动 Class.forName("com.mysql.jdbc.Driver"); //2.用户信息和url String url = "jdbc:mysql://localhost:3306/wsddd?"; String name = "root"; String pwd = "Wsd246503"; //3.连接成功,数据库对象,connection代表数据库 Connection connection = DriverManager.getConnection(url, name, pwd); //4.执行SQL的对象 statment 执行SQL的对象 Statement statement = connection.createStatement(); //5.执行SQL对象去执行SQL,可能存在结果,返回查看结果 String sql = "SELECT * FROM orders"; ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()){ System.out.println("order_num "+ resultSet.getObject("order_num")); System.out.println("order_date "+ resultSet.getObject("order_date")); System.out.println("order_date "+ resultSet.getObject("order_date")); System.out.println("====="); } //6.释放资源 resultSet.close(); statement.close(); connection.close();a } }