本例通过jdbc对MySQL进行查询操作
public class First {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost/tim"; //数据库位置
ResultSet resultSet = null;
Statement sta = null;
Connection connection = null; //扩大类作用范围
try { //主体部分
Class.forName("com.mysql.jdbc.Driver"); //注册
/* Connection con = DriverManager.getConnection(url, "root","hello"); //连接方式一
System.out.println(con);
*/
//properties
Properties pro = new Properties();
pro.setProperty("user","root");
pro.setProperty("password","hello");
connection = DriverManager.getConnection(url, pro); //连接方式二
//statement
String sql = "select * from student";
// String sql = "insert into student values (4,'xienana')";
sta = connection.createStatement();
resultSet = sta.executeQuery(sql);//执行查询的操作。select等
// int i = sta.executeUpdate(sql);// 这个用来执行,增删改的操作,insert、update、delete
while(resultSet.next()){
int i = resultSet.getInt(1);
String name = resultSet.getString("name");
System.out.println(i + " = " + name);
}
// System.out.println("受影响的行数为" + i);
} catch (Exception e) { //释放资源
e.printStackTrace();
} finally {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
sta.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}