第一个JDBC入门程序

系统环境

  • Java版本:Java8
  • 开发环境:eclipse
  • 所需jar包:mysql-connector-java-5.1.7-bin.jar
  • MySQL版本:MySQL5.7
  • windows版本:win10

示例代码

package com.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCDemo1 {
	
	public static void demo1() {
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			// 1.加载驱动
			//DriverManager.registerDriver(new Driver()); // 会注册两次
			Class.forName("com.mysql.jdbc.Driver");
			// 2.获得连接
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "sky06xky");
			// 3.创建执行SQL的对象,并且执行其语句
			// 3.1创建执行SQL的对象
			String sqlString = "select * from user";
			statement = connection.createStatement();
			// 3.2执行sql语句
			resultSet = statement.executeQuery(sqlString);
			while (resultSet.next()) {
				int uid = resultSet.getInt("uid");
				String usernameString = resultSet.getString("username");
				String passwordString = resultSet.getString("password");
				String nameString = resultSet.getString("name");
				System.out.println(uid+"   "+usernameString+"   "+passwordString+"   "+nameString+ "   ");
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			// 4,释放资源
			if (resultSet != null) {
				try {
					resultSet.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				resultSet = null;
			}
			if (statement != null) {
				try {
					statement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
				statement = null;
			}
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public static void main(String[] args) {
		demo1();
	}
}

 

大致开发步骤

  • 注册MySQL数据库驱动,并加载其驱动
  • 获得一个数据库连接
  • 创建执行SQL的对象,并编写其SQL语句
  • 释放所用到的资源

其中第四步是及其重要的,因为要及时的释放,才能让其服务器的资源不至于那么的紧张。

释放资源的关键代码

if (resultSet != null) {
	try {
		resultSet.close();
	} catch (SQLException e) {
		e.printStackTrace();
	}
	resultSet = null;
}
if (statement != null) {
	try {
		statement.close();
	} catch (SQLException e) {
		e.printStackTrace();
	}
	statement = null;
}
if (connection != null) {
	try {
		connection.close();
	} catch (SQLException e) {
		e.printStackTrace();
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值