JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。
如果要使用数据库就要添加数据库的驱动,不同的数据库有不用的驱动,这里就不一一说明,添加jar程序驱动包的方法就不在这里解释
下面是jdbc对mysql数据库的增删查改
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MysqlUtil {
public static void main(String[] args) throws SQLException {
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet r=null;
//连接mysql的url
String url="jdbc:mysql://localhost:3306/mydb?user=root&password=mysql";
try {
//加载mysql驱动
Class.forName("com.mysql.jdbc.Driver");
//连接
connection=DriverManager.getConnection(url);
System.out.println(connection);
//mysqljdbc添加数据
// String sql="insert into users(userid,username,pwd) values(1,'擎天柱','123')";
// PreparedStatement preparedStatement=connection.prepareStatement(sql);
// int i=preparedStatement.executeUpdate();
// if(i==1){
// System.out.println("添加成功");
// }else{
// System.out.println("添加失败");
// }
//mysqljdbc查询数据
// String sql="select * from users";
// preparedStatement=connection.prepareStatement(sql);
// r=preparedStatement.executeQuery();
// while(r.next()){
// System.out.println(r.getString("userid")+r.getString("username")+r.getString(3));
// }
//修改数据
// String sql="update users set pwd=? where userid=?";
// preparedStatement=connection.prepareStatement(sql);
// preparedStatement.setString(1,"qingtianzhu");
// preparedStatement.setInt(2, 1);
// int i=preparedStatement.executeUpdate();
// if(i==1){
// System.out.println("修改成功");
// }else{
// System.out.println("添加失败");
// }
//删除数据
String sql="delete from users where userid=?";
preparedStatement=connection.prepareStatement(sql);
preparedStatement.setInt(1, 2);
int i=preparedStatement.executeUpdate();
if(i==1){
System.out.println("删除成功");
}else{
System.out.println("删除失败");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
// r.close();
preparedStatement.close();
connection.close();
}
}
}