最简单的格式如下:
private static void learnJdbc() throws SQLException {// 注册驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//获取连接
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mm","root","123");
//获取操作sql语句的对象
Statement sm=conn.createStatement();
String sql="select *from users;";
//获取以上操作后返回的结果集
ResultSet rs=sm.executeQuery(sql);
while(rs.next()){
System.out.println("id\t"+rs.getObject(1));
System.out.println(rs.getObject(2));
System.out.println(rs.getObject(3));
System.out.println(rs.getObject(4));
System.out.println(rs.getObject(5));
}
rs.close();
sm.close();
conn.close();
}
标准的流程应该如下:
大概的步骤:(首先要添加入jdbc的jar包和安装好MySQL数据库)
1、注册jdb驱动,建议通过类加载器实现。 2、通过DriverManager获取一个连接Connection 3、通过Connection中获取一个Statement(建议使用其子类PreParedStatement)用于执行静态 SQL 语句并返回它所生成结果的对象。 4、通过Statement 获取一个返回的结果集ResultSet,然后遍历该结果集,转成javaBean就可以了。 5、至于如何改变数据库的数据,直接在第3步通过sql语句就可以实现数据的executeUpdate()->增删改,executeQuery()->查.
private static Connection conn=null;
// private static Statement sm=null;
private static ResultSet rs=null;
private static PreparedStatement ps=null;
public static void main(String[] args) {
Map myMap=new HashMap();
myMap.put("liuyan", "123456");
myMap.put("baoqiang", "13321");
myMap.put("fangbian", "abc");
myMap.put("miejuesh", "12132sdfsjfs545");
Set mSet=myMap.keySet();
for (String key : mSet) {
System.out.println(myMap.get(key));
}
try {
// DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//通过类加载器,加载jdbc驱动,上面的方法其实是创建了2次该对象
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mm","root","123");
// sm=conn.createStatement();
String sql="select name from userinfo";
//使用prepareStatement是Statement的子类,具有防SQL语句注入的功能,而Statement没有该功能。
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();//执行DQL语句的。
// ArrayList lists=new ArrayList<>();
while(rs.next()){
//通过结果集获取查询得到的数据
String name=(String) rs.getObject("name");
System.out.println("刚开始"+name);
for (String key : mSet) {
if(name.equals(key)){
System.out.println("用户已存在");
}else{
//此处可以用?来防止sql注入
String esql="insert into userinfo value(?,?)";
ps.setString(1, key);
ps.setString(2, myMap.get(key));
int flag=ps.executeUpdate();//执行DML语句的
// sm.execute(esql, columnNames)
System.out.println("修改了"+flag+"行");
}
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("异常了");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs=null;
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ps=null;
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn=null;
}
}
},>,>
至于事务,下期更新。。。。。。。。。。。。。。。。。。。。