Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@localhost:1521:xe";
String usrt="hr";
String possword="123";
Connection connection= DriverManager.getConnection(url,usrt,possword);
System.out.println("连接成功 ");
1行,把全类名为oracle.jdbc.driver.OracleDriver导入到jvm里面
2行,设置orcale地址
3行,依次传入用户名和密码connection来进行连接
String url="jdbc:mysql://localhost:3306/test?characterEncoding=utf8";
String user="root";
String possword="123";
Connection con= DriverManager.getConnection(url,user,possword);
这个为mysql的连接设置大致操作和orcale相差无几,不过在url里面test为数据库的名字后面要添加字符编码,否则在实际操作的时候会产生错误,也就是添加中文字符的时候会出现问号
String sql="Insert into regions(region_id,region_name) values (?,?)";
PreparedStatement preparedStatement=connection.prepareStatement(sql);//传入sql语句
String regin_name="上海";
Integer regin_id=8;
preparedStatement.setInt(1,regin_id);
preparedStatement.setString(2,regin_name);
preparedStatement.executeUpdate();
使用preparedStatement方法来对数据库进行增加
or映射,和map有点类似
Statement statement=connection.createStatement();
String sql2="select *from REGIONS ";
ResultSet rs=statement.executeQuery(sql2);
List<Person> as=new ArrayList<>();
while (rs.next()){
as.add(new Person(rs.getInt(1),rs.getString(2)));
}
rs.close();
as.stream().forEach((a)-> System.out.println(a.getRegion_id()));
网友评论