日期:12月7日 星期一
一个简单的案例
public class JdbcDemo1 {public static void main(String[] args) throws Exception {//1,导入驱动jar包//新建libs文件夹,并向其导入jar包,然后右击Add as Library//2,注册驱动Class.forName("com.mysql.cj.jdbc.Driver");//3,获取数据库的连接对象Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/selecttest", "root", "zk123");//4,定义Sql语句String sql="update student set s_class=95555 where s_no=101";//5,获取执行sql的对象 StatementStatement stmt = conn.createStatement();//6,执行sqlint count = stmt.executeUpdate(sql);//7,处理结果System.out.println(count);//8,释放资源conn.close();stmt.close();}}
获取数据库的连接:
方法:public static Connection getConnection(String url, String user, String password)
参数:
url: 指定连接的路径- 语法:jdbc:mysql://ip地址(域名):端口号、数据库名称- 例子:
jdbc:mysql://localhost:3306/selecttest
- 细节:如果连接的是本机mysql服务器,并且mysql服务器默认端口是3306,则url可以简写为:jdbc:mysql://数据库名称
user:用户名
password:密码
