java基础--JDBC

一.JDBC

JDBC是java提供的一套类和接口,是连接数据库的一套规范.

JDBC操作数据库的步骤
1.注册驱动加载驱动类
2.获取数据库连接对象
getConnection(url,user,password)
3.通过连接对象 获取sql语句的执行对象statement
4.通过statement对象来执行sql语句
executeUpdate(sql) 返回值 int类型 用于执行DDL,DML语句
executeQuery(sql) 返回值 Resultset 用于执行DQL
5.处理执行sql后得到的结果集
6.关闭资源

如何处理结果集?
ResultSet resultset = statement.executeQuery(sql);

while(resultset.next()){
1.result.get类型(int)
如果使列用索引
注意从1开始
如果使用*查询 索引是数据库表中的顺序
如果不使用*直接使用字段
那么顺序就是你在sql语句中使用的顺序

2.result.get类型("字段名")
}

二.获取预编译sql语句的对象

目的:防止sql注入
//使用占位符 问号?
//注意使用问号占位符 不用加单引号
String sql = "select * from users where username=? and password=?";
PreparedStatement statement = connection.prepareStatement(sql);
设置占位符的值
 参数1 问号的索引 从1开始
 参数2 替换问号的值
 statement.setObject(1, username);
 statement.setObject(2, pass);

三.编写一个JDBC连接工具类

public class JDBCUitl {
	//声明连接为成员变量
	private static Connection connection;
	private static String driverClass;
	private static String username;
	private static String url;
	private static String password;
	//私有化构造方法
	public JDBCUitl() {
		
	}
	//静态代码块
	static {
		try {
			readProperites();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			Class.forName(driverClass);
		} catch (ClassNotFoundException e) {
			// 注册失败 没有执行下去的意义
			//直接抛出运行时异常
			throw new RuntimeException("数据库加载失败");
		}
	}
	//提供一个get方法 获取连接使用
	public static Connection getConnection() {
		try {
			connection =  DriverManager.getConnection(url,username,password);
		} catch (SQLException e) {
			throw new RuntimeException("数据库连接异常");
		}
		return connection;
	}
	public static void readProperites() throws IOException {
		Properties properties = new Properties();
		InputStream inputStream = JDBCUitls.class.getClassLoader().getResourceAsStream("db.properties");
		properties.load(inputStream);
		driverClass = properties.getProperty("driverClass");
		url = properties.getProperty("url");
		username = properties.getProperty("username");
	    password = properties.getProperty("password");
	}
	//关闭资源
	//把需要要关闭的资源当做参数传进来
	public static void close(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet) {
		//判断不为空再关闭
		if (connection!=null) {
			try {
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (preparedStatement!=null) {
			try {
				preparedStatement.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (resultSet!=null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}

猜你喜欢

转载自blog.csdn.net/hehanhh/article/details/80697182
今日推荐