如使用JDBC连接Mysql数据库

原来JDBC连接数据库连接竟然这么简单!

  1. 加载驱动
  2. 创建连接
  3. 进行预编译
  4. 执行sql语句
  5. 释放资源

代码1

public class Demo01 {
public static void main(String[] args) throws Exception{
	//加载驱动
	Class.forName("com.mysql.jdbc.Driver");
	//连接数据库
	Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/day06", "root", "root");
	Statement stm= conn.createStatement();
	 int r=stm.executeUpdate("insert into stu(id,username,age)values(6,'刘备',45)");
	 if(r>0) {
		 System.out.println("执行成功");
	 }else {
		 System.out.println("失败");
	 }
	 //System.out.println("受影响行数:"+r);
	 stm.close();
	 conn.close();
	
	}
}

代码2

public class Demo2 {
	public static void main(String[] args) {
		Connection conn=null;
		Statement stm=null;
		ResultSet result=null;
		
		try {
			//加载驱动
			Class.forName("com.mysql.jdbc.Driver");
			//创建连接
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day06","root", "root");
			stm=conn.createStatement();
			//int r=stm.executeUpdate("insert into stu(id, username,age) values(7,'貂蝉',18)");
			//int  r=stm.executeUpdate("delete  from stu where id=1");
			//int r=stm.executeUpdate("update stu set username='西施' where id=4");
			result=stm.executeQuery("select* from stu");
			if(result!=null) {
				System.out.println("编号\t姓名\t年龄");
			}
			while(result.next()) {
				int id=result.getInt(1);
				String  username=result.getString("username");
				int age=result.getInt("age");
				System.out.println(id+"\t"+username+"\t"+age);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			//释放结果
			try {
				if(result!=null) {
					result.close();
				}
				if(stm!=null) {
				stm.close();
				}
				if(conn!=null) {
					conn.close();
				}	
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

注意
localhost:默认的是本机的端口号(127.0.0.1)
Mysql的默认端口号:3306
第一个root:数据库名
第二个root:数据库密码

简单的总结JDBC连接数据库5个字:加连预执释

jar包:
jdbc连接的jar包

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值