工程:
JDBC (Java DataBase Connectivity) Java数据库连接;
JDBC组成:①java.sql包中;②对应数据厂商提供
JDBC的使用步骤:
一、:连接数据库:①加载驱动;(利用反射把驱动加载进虚拟机,静态代码块就是在加载驱动)②获取连接对象;url=jdb:mysql://host:port/database_name;
二:创建语句状态对象;
三:执行SQL语言;
四:释放资源。
下面来一个测试类:
public class JDBC_tree { @Test public void JDBC_test() throws Exception { //连接 Class.forName("com.mysql.jdbc.Driver");//驱动加载 Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/car", "root", "root");//获取连接对象 Statement Stater = connection.createStatement();//创建连接语句 String A = "CREATE TABLE animal(a_name varchar(20),a_age int,a_num int)";//创建表的命令 //执行语句 Stater.executeUpdate(A); //释放资源 Stater.close(); connection.close(); } }
public class JDBC_tree { @Test public void JDBC_test() throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/car", "root", "root"); Statement Stater = connection.createStatement();//创建连接语句 ResultSet executeQuery = Stater.executeQuery( "SELECT *FROM animal"); while (executeQuery.next()){ String string = executeQuery.getString("a_name"); int int1 = executeQuery.getInt("a_num"); System.out.println(string +"="+int1); } Stater.close(); connection.close(); } } //建一个类,私有化里面的字段,生成geter和seter方法和tostring方法 public class A { private int age; private String name; private int num; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String toString() { return "A [age=" + age + ", name=" + name + ", num=" + num + "]"; } }