连接数据库

如何连接数据库?

代码如下(示例):

package com.vetor.lesson;

import java.sql.*;

public class Example11_1 {
	public static void main(String[] args) {
		Connection con = null;
		Statement sql;
		ResultSet rs;
		try {
		Class.forName("com.mysql.jdbc.Driver");  //加载JDBC-MySql驱动
		}catch(Exception e) {
			System.out.println("名字错误了!!!");
		}
		String uri = "jdbc:mysql://localhost:3306/students?useSSL=true";
		String user = "root";
		String password ="";
		try {
			con = DriverManager.getConnection(uri,user,password);
		}catch(SQLException e) {
			System.out.println("检查是否错误");
		}
		try {
			sql = con.createStatement();  //得到SQL语句对象
			rs = sql.executeQuery("SELECT * FROM mess"); //得到ResultSet对象
			while(rs.next())
			{
				String number = rs.getString(1);
				String name = rs.getString(2);
				Date date = rs.getDate(3);
				float height = rs.getFloat(4);
				System.out.printf("%s\t",number);
				System.out.printf("%s\t",name);
				System.out.printf("%s\t",date);
				System.out.printf("%.2f\n",height);
			}
			con.close(); //关闭连接
		}
		catch(SQLException e)
		{
			System.out.println(e);
		}
	}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值