JDBC连接MariDB数据
简介
因为JDBC是比较常用的操作,然后网上大部分又都是连接mysql的教程(虽然都换汤不换药)。合适的连接maridb的教程自己有时候要找半天。然后就特地把基本的步骤和详细操作代码写一下,以后找也方便。
代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class JDBCDemo1 {
public static void main(String[] args) throws Exception {
//1、导入jar包
//2、注册驱动
// 因为连接的是maridb,所以注册的驱动固定为:org.mariadb.jdbc.Driver
//若连接的是mysql,则驱动为:com.mysql.jdbc.Driver
Class.forName("org.mariadb.jdbc.Driver");
//3、获取数据库连接对象 我这访问的数据库为db1,用户名为root,密码为空
Connection connector = DriverManager.getConnection("jdbc:mariadb://localhost:3306/db1", "root", "");
//4、定义sql语句
String sql="update emp set sal=5000 where id=18003";
//5、获取执行sql语句的对象
Statement statement = connector.createStatement();
//6、执行sql语句
int cnt = statement.executeUpdate(sql);
//7、处理结果(单纯看执行是否成功)
System.out.println(cnt);
//8、释放资源
statement.close();
connector.close();
}
}