步骤
加载驱动
创建连接
获取statement
执行代码
得到结果
注意:user 和 password
这个java.sql 是java的公司发布的一个接口,各数据库厂商按接口写的功能。所以java里操作不同的数据库用的代码一样
这里用的是执行静态的sql语句的,
//注册驱动
//不能用DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //由于参数里创建新对象的时候Driver类里有静态代码在类加载是自动执行进行注册驱动,所以这一句会注册两个驱动,多以不用这句
Class.forName("com.mysql.jdbc.Driver");
//这一句是要加载这个类,返回值不知道咋用。
//method 1
// Connection connection = DriverManager.getConnection("JDBC:Mysql://localhost:3306/ljj","root","root");
//method 2
// Connection connection = DriverManager.getConnection("JDBC:Mysql://localhost:3306/ljj?user=root&password=root");
//method 3
Properties pro = new Properties();
//method 3.1
// pro.setProperty("user","root");
// pro.setProperty("password","root");
//method 3.2
pro.load(new FileInputStream("./com/yh/db.properties"));
Connection connection = DriverMa
nager.getConnection("JDBC:Mysql://localhost:3306/word", pro);
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("select * from english_words where word = 'aaaaa' limit 4;"); //增用这个方法,删改查用executeUpdate() 返回值是int。
while (result.next()) {
System.out.println(result.getString(2) + "\t" + result.getString(3)); //string可以用getInt取,只要内容是数字
}
statement.close();
result.close();
connection.close();</code></pre></div> <div style="width: 100%; max-width: 996px; margin-top: 2px;">
<div style="color: inherit; fill: inherit;">
<div style="display: flex;">
评论区