Java之简单的jdbc连接数据库

版权声明:《==study hard and make progress every day==》 https://blog.csdn.net/qq_38225558/article/details/82837750

步骤:

1.加载驱动
2.获取连接:与数据库建立连接
3.sql预编译对象:预编译对象
4.执行sql语句
5.释放资源
public class JDBCDemo {

	public static void main(String[] args) {
		Connection connection = null;
		Statement statement = null;
		try {
			//1.加载驱动
			Class.forName("com.mysql.jdbc.Driver");
			//2.获取连接:与数据库建立连接
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/zhengqing_test", "root", "root");
			//3.获得sql的预编译对象
			statement = connection.createStatement();
			//4.执行sql语句    ex:创建表t_user
			String sql = "CREATE TABLE t_user("
					+" `id` int(11) NOT NULL,"
					+" `username` varchar(20) NOT NULL,"
					+" `password` int(11) NOT NULL,"
					+"  PRIMARY KEY (`id`)"
					+"  ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
			statement.executeUpdate(sql);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//5.释放资源      (注意:关闭资源顺序 先打开后关闭)
//			statement.close();
//			connection.close();
			try {
				if(statement!=null) {
					statement.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				try {
					if(connection!=null) {
						connection.close();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			/*方式二:
			try {
				if(statement!=null) {
					statement.close();
				}
				if(connection!=null) {
					connection.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
		}	
	}
		
}

猜你喜欢

转载自blog.csdn.net/qq_38225558/article/details/82837750