数据库连接,及实现数据库数据的增,删,改,查

时间:2022-12-11 20:27:53

package com.lanqiao.javatest;


import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Properties;

import org.junit.Test;

import com.mysql.jdbc.Statement;

 

 

public class TestDriverManager {
/*
* 连接数据库的方法:
* 1.使用DriverManager连接数据库
* 2.Driver连接:是一个接口,是一个本地实现的接口,能从其中获取数据库的驱动的链接
* */

//方法一:DriverManager方法,连接数据库

public void testDriverManager() throws Exception{
//连接数据库的四个要素:
String driverClass=null;
String jdbcUrl=null;
String user=null;
String password=null;

//读取类路径文件下的jdbc.properties
InputStream in=
getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
properties.load(in);//从输入流中读取文件

//依次获取properties中的文件
driverClass=properties.getProperty("driver");
jdbcUrl=properties.getProperty("jdbcUrl");
user=properties.getProperty("user");
password=properties.getProperty("password");

Class.forName(driverClass);//反射机制获取文件中的driverClass

//通过driverManager中的getConnection方法获取数据的连接
Connection conn=DriverManager.getConnection(jdbcUrl,user,password);
System.out.println(conn);
}

//方法二:使用driver接口连接数据库
//1.
public Connection getConnection() throws Exception{
//连接数据里的四个必要步骤:
String driverClass=null;
String jdbcUrl=null;
String user=null;
String password=null;

//读取类路径文件下的jdbc.properties文件
InputStream in=getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
//从输入流中读取文件
properties.load(in);

//依次获取文件中的内容
driverClass=properties.getProperty("driver");
jdbcUrl=properties.getProperty("jdbcUrl");
user=properties.getProperty("user");
password=properties.getProperty("password");

//反射机制获取
@SuppressWarnings("unused")
Driver driver=(Driver)Class.forName(driverClass).newInstance();//获取运行时类的方法及属性

Properties info=new Properties();
info.put("user", "root");
info.put("password", "lxn123");
Connection conn=driver.connect(jdbcUrl, info);
return conn;
}
@Test
//测试testDriver()方法;
public void testDriver1() throws Exception{
System.out.println(getConnection());
}
/*
* 1.连接数据库之后对指定的数据库中的增加,删除,更改,查询的操作
* statement用于执行sql语句的对象;
* 通过Connection的stateStatement()方法来获取
* 同过executeUpdate(sql)可以执行sql语句
* 传入的sql语句可以是insect(插入),update(修改),delete(删除),但是不可以是select(查询)
* 2.需要注意的是:Connection,statement都是应用程序和数据库服务器的链接资源,使用后都要关闭;
* */
@Test
public void testStatement() throws Exception{//数据库的插入,删除,更改,查询需要的步骤;
//1.获取数据库的
Connection connn=getConnection();
//2.准备插入的sql语句

//将sql语句插入到在数据库中建立的表格中
String sql="INSERT INTO CUSTOMER(NAME,EMALL,BIRTH)VALUES('ABDC','LJSD','1992-2-12');";

//4.进行插入,删除,更改,查询的操作
//获取sql语句的statement对象,调用statement对象的executeUpdate(sql),执行sql语句的插入
Statement statement=(Statement) connn.createStatement();
statement.executeUpdate(sql);
//5关闭statement对象。
statement.close();
//3.关闭连接
connn.close();
}
}