创建一个数据库,前提还得检测数据库是否已经存在。
穿建表同样的道理。
在连接的时候,不需要输入数据库
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
public class ClassJDBC {
public static void main(String[] args) throws Exception {
String url="jdbc:mysql://localhost:3306/?allowPublicKeyRetrieval=true&useSSL=false";
String user="root";
String pw="root";
Connection con =DriverManager.getConnection(url,user,pw);//获得数据库链接对象
PreparedStatement ps=con.prepareStatement ("SHOW DATABASES LIKE \"test\"");
ResultSet rs=ps.executeQuery();
if(rs.next())//判断数据库是否存在
System.out.println("数据库存在");
else{//创建test数据库
ps=con.prepareStatement("CREATE DATABASE test");
ps.executeUpdate();//执行sql语句
System.out.println("数据库创建成功");
}
con.prepareStatement("USE test").execute();//使用test 表
ps=con.prepareStatement("SHOW TABLES LIKE \"student\"");
rs=ps.executeQuery();
if(rs.next())
System.out.println("表已存在");
else {
ps=con.prepareStatement("CREATE TABLE student (id INT(11) PRIMARY KEY ,name VARCHAR(25) ) " );
ps.executeUpdate();
System.out.println("表创建成功");
}
HashMap<Integer,String> hm=new HashMap<>();
hm.put(1000,"小明");
hm.put(1001,"小红");
hm.put(1002,"小望");
ps=con.prepareStatement("INSERT INTO student VALUE (? ,? )");//增
for(Map.Entry<Integer,String> map:hm.entrySet()){
ps.setObject(1,map.getKey());
ps.setObject(2,map.getValue());
ps.addBatch();
}
ps.executeBatch();
ps=con.prepareStatement("DELETE FROM student WHERE id=?");//删
ps.setObject(1,1000);
ps.executeUpdate();//执行sql语句
ps=con.prepareStatement("UPDATE student SET name=? WHERE id=?");//改
ps.setObject(1,"小昕");
ps.setObject(2,1001);
ps.executeUpdate();
ps=con.prepareStatement("SELECT * FROM student ");
rs=ps.executeQuery();//查
while(rs.next()){
int id=rs.getInt(1);
String name=rs.getString(2);
System.out.println(id+":"+name);
}
con.close();
rs.close();
}
}