jdbc连接数据库

package com.huawei.jdbc;

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

import com.huawei.utils.DBUtil;

public class TestJDBC01 {

/**
* 要操作数据库
*
*
* 可以将数据量理解为一个仓库
*
* 如果 要将东西放进去 则需要钥匙 (数据库驱动)
*
* 用钥匙(驱动)去将仓库(数据库)打开 然后存储数据
* @throws SQLException
* @throws ClassNotFoundException
*
*
* 操作数据库的步骤
*
* 1、加载驱动
*
* 2、得到连接
*
* 3、操作数据库
*
* 4、关闭资源
*
*
*/

public static void main(String[] args) throws Exception {


/**
*
* 获取连接Connection的方式
*
* 第一种:
* Class.forName()加载指定的驱动类 并生成对象 放到DriverManager中管理 com.mysql.jdbc.Driver
*
* 第二种:
* 在类路径下 提供 META-INF/services/java.sql.Driver 文件 在文件里面协商驱动的全局限定名
*
*
* 得到Connection的步骤
*
* 显示或是隐式加载驱动到 DriverManager中
*
* 再由得到的驱动对象去根据提供的数据去得到连接
*
*
*
*
*
*
*
*
*/

//Class.forName("com.mysql.jdbc.Driver");

//Connection connection = null;
//关于在JDBC中的URL

//jdbc:数据库类型://地址:端口/数据库名
//connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");

//System.out.println(connection);

//testExecuteQuery();

//testExecuteUpdate();
testUpdate();
}



public static void testExecuteQuery() throws SQLException, ClassNotFoundException{
Class.forName("com.mysql.jdbc.Driver");
//得到连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
//得到sql语句的执行者
Statement statement = connection.createStatement();
//有sql执行者去执行sql语句
//执行sql语句的方式
//一种是主要针对查询的 一定会返回一个结果集
//一种主要是针对查询以外的 会返回一个受影响的行数
ResultSet rs = statement.executeQuery("SELECT * from users");
//变量结果集
/*while(rs.next()){
System.out.println(rs.getString(1)+":"+rs.getObject(2));
}*/
//rs.
System.out.println("---------------------");
while(rs.next()){
System.out.println(rs.getString("password")+":"+rs.getObject("username"));
}
//释放资源 关闭顺序
//ResultSet statement connection
rs.close();
statement.close();
connection.close();

}

/**
*
*/
public static void testExecuteUpdate() throws Exception{
//显示加载驱动
Class.forName("com.mysql.jdbc.Driver");
//得到连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
//sql语句执行者
Statement statement = connection.createStatement();

//String sql = "insert into users (username,password) values ('wangwu','123123456')";
String sql = "INSERT INTO users (username,password) VALUES ('wangwu','123123456')";

int num = statement.executeUpdate(sql);

System.out.println(num);

statement.close();

connection.close();
}

public static void testUpdate() throws Exception{
//得到连接
Connection connection = DBUtil.getConnection();
//语句执行者
Statement statement = connection.createStatement();
String sql = "UPDATE users SET password='abcd123' WHERE username='wangwu'";

int num = statement.executeUpdate(sql);

System.out.println(num);

DBUtil.close(statement,connection);


/**
* Statement 会有 一个关于sql注入的bug 所以 基本不使用
*/

}

}

原文地址:https://www.cnblogs.com/hwgok/p/5814607.html