使用jdbc连接mysql数据库,首先需要引入mysql的驱动jar包:
创建名为cloudb01的数据库,然后建部门表:
CREATE TABLE `dept` (
`deptno` int(10) NOT NULL AUTO_INCREMENT,
`dname` varchar(255) DEFAULT NULL,
`db_source` varchar(255) DEFAULT NULL,
PRIMARY KEY (`deptno`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
之后就可以上手写demo了,具体代码如下:
1、新增操作
public class JdbcPractice{
public static void main(String[] args){
try{
Class.forName(“com.mysql.jdbc.Driver”);
String username = “root”;
String password = “root”;
String url = “jdbc:mysql://localhost:3306/clouddb01”;
Connection con = DriverManager.getConnection(url, username, password);
String sql = “insert into dept(deptno,dname,db_source) values(?,?,?)”;
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, 12);
ps.setString(2, “财务部”);
ps.setString(3, “clouddb01”);
int count = ps.executeUpdate();
if(count>0){
System.out.println(“数据插入成功,条数为:”+count);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
2、查询操作
public class JdbcPractice{
public static void main(String[] args){
try{
Class.forName(“com.mysql.jdbc.Driver”);
String username = “root”;
String password = “root”;
String url = “jdbc:mysql://localhost:3306/clouddb01”;
Connection con = DriverManager.getConnection(url, username, password);
String sql = “select * from dept”;
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
while(rs.next()){
System.out.println(“部门编号为:”+rs.getInt(1)+”,部门名称为:”+rs.getString(“dname”)+”,所属数据库为:”+rs.getString(“db_source”));
}
} catch (Exception e)
{
e.printStackTrace();
}
}
由于新增、删除和修改的方法差不多,只是sql有些出入,就不一一展示了。