欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JDBC连接数据库配置

程序员文章站 2022-06-17 13:33:41
...
jdbc:sqlserver://localhost:1433;
databaseName=stufeedb;
integratedSecurity=true;
user=sa;
password=svse;

 

package com.singlee.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class DBHelper {
	public static Connection conn = null;

	/**
	 * 获取连接 通过配置文件的方式获取数据库连接,使JDBC操作数据库具有一定的灵活性
	 */
	public DBHelper() {

		Properties pro = new Properties();
		try {
			// 读取配置文件
			pro.load(DBHelper.class
					.getResourceAsStream("jdbc_sqlserver.properties"));
			String Driver = pro.getProperty("Driver");
			String url = pro.getProperty("url");
			String user = pro.getProperty("user");
			String password = pro.getProperty("password");
			// 加载驱动
			Class.forName(Driver);
			// 获取连接
			conn = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭连接,节约资源
	 */
	public static void close() {
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取数据库连接
	 * 
	 * @return
	 */
	public static Connection getConn() {
		new DBHelper();
		return conn;

	}
}

 

package com.singlee.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class DBConnTest {

	public static void main(String[] args) {
		sybaseConnTest();

	}

	/**
	 * Sybase数据库连接测试
	 */
	public static void sybaseConnTest(){
		 try {
	            Class.forName("com.sybase.jdbc3.jdbc.SybDriver").newInstance();
	            String url = "jdbc:sybase:Tds:127.0.0.1:5000/yxt";// 数据库名
	            Properties sysProps = System.getProperties();
	            sysProps.put("user", "sa"); // 设置数据库访问用户名
	            sysProps.put("password", ""); // 密码
	            Connection conn = DriverManager.getConnection(url, sysProps);
	            Statement stmt = conn
	                    .createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
	                            ResultSet.CONCUR_UPDATABLE);
	            String sql = "select userid,username from tb_user"; // 表
	            ResultSet rs = stmt.executeQuery(sql);
	            while (rs.next()) {
	                System.out.println("userid:"+rs.getString(1)+",username:"+rs.getString(2)); // 取得第二列的值
	            }
	        } catch (Exception e) {
	        	e.printStackTrace();
	            System.out.println("sybaseConnTest Exception:"+e.getMessage());
	        }
	}
}