JDBC学习使用纯java方式连接数据库

java学习-JDBC

访问数据库流程:

-加载JDBC驱动程序

-建立与数据库的连接

-发送SQL查询

-得到查询结果

package week9.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/*
 * 使用纯java方式连接数据库
 */
public class demo1 {
	public static void main(String[] args) {
		Connection conn = null;
		try {
			//加载驱动类
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("加载驱动成功");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			System.out.println("加载驱动失败");
		}
		
		try {
			//建立连接
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");//test为数据库名称
			System.out.println("建立连接成功");
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			System.out.println("建立连接失败");
		} finally {
			try {
				//关闭连接
				conn.close();
				System.out.println("关闭连接成功");
			} catch (SQLException e) {
				e.printStackTrace();
				System.out.println("关闭连接失败");
			}
	}

}
}

猜你喜欢

转载自blog.csdn.net/IT_world_/article/details/90040169
今日推荐