mysql数据库连接

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值