jdbc连接数据库之修改

2025-10-26 22:50:13

1、mysql加载数据库

driver=com.mysql.jdbc.Driver

数据库的链接url=jdbc:mysql://localhost:3306/demo1

用户名username=root

密码password=123456

设置配置文件信息

jdbc连接数据库之修改

2、属性的定义

public class DBUtil { private static Properties properties = new Properties(); private static String driver; private static String url; private static String username; private static String password; static{

jdbc连接数据库之修改

3、  // 获取配置文件中的相关参数值  try {

读取配置文件   properties.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));   driver = properties.getProperty("driver");            url=properties.getProperty("url");            username=properties.getProperty("username");            password=properties.getProperty("password");    

jdbc连接数据库之修改

4、        try {    Class.forName(driver);   } catch (ClassNotFoundException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }  } catch (IOException e) {   System.out.println("加载文件失败");  } }

jdbc连接数据库之修改

5、  //连接数据库的方法 public static Connection getConnection() throws SQLException{    Connection con=null;  con=DriverManager.getConnection(url,username,password);    return con; }  //关闭数据库的方法 public static void closeConnection(Connection con){  try {   con.close();  } catch (SQLException e) {   System.out.println("关闭资源失败");  } }}

jdbc连接数据库之修改

6、public class Test { public static void main(String[] args) {  Connection con =null;  try {   con=DBUtil.getConnection();  } catch (SQLException e) {   // TODO Auto-generated catch block   e.printStackTrace();  }finally{     DBUtil.closeConnection(con);  }  System.out.println(con); } }

jdbc连接数据库之修改

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢