package Test;
import java.nio.file.*;
import java.sql.*;
import java.io.*;
import java.util.*;
public class TestDB {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
try
{
runTest();
}
catch(SQLException ex)//枚举所有异常
{
for(Throwable t:ex)
t.printStackTrace();
}
System.exit(0);
}
public static void runTest() throws SQLException,IOException
{
try(Connection connection=getConnection())
{
Statement stat=connection.createStatement();//执行SQL命令之前,首先需要创建一个Statement对象,要创建Statement对象,需要使用调用
//DriverManager.getConnection方法所获得的connection对象
//stat.executeUpdate("CREATE TABLE huhu (Message CHAR(20)");//执行更新,插入删除类的操作使用,但查询语句时,必须使用executeQuery(返回一个ResultSet对象)
//stat.executeUpdate("INSERT INTO huhu VALUES('Hello,Word!')");
try(ResultSet result= stat.executeQuery("SELECT *FROM person"))
{
if(result.next())
System.out.println(result.getString(2));
}
//stat.executeUpdate("DROP TABLE huhu");
}
}
public static Connection getConnection() throws SQLException,IOException
{
Properties props=new Properties();
try(InputStream in=Files.newInputStream(Paths.get("sof/database.properties")))
{
props.load(in);
}
String drivers=props.getProperty("mysql.drivers");
if(drivers!=null)
System.setProperty("mysql.drivers", drivers);
String url=props.getProperty("mysql.url");
String username=props.getProperty("mysql.user");
String password=props.getProperty("mysql.pwd");
return DriverManager.getConnection(url,username,password);
}
}
database.properties
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://127.0.0.1:3306/greatings
mysql.user=root
mysql.pwd=root
mysql.port=3306