📄 dbconnectionmanager.java
字号:
package electric.electricUtils;
import java.sql.*;
import java.util.*;
import java.io.*;
/*此类是经常使用的连接数据库的DbConnectionManager.java类*/
public class DbConnectionManager
{
//从FinalConstants类中读取保存数据库信息的配置文件
private static String propFileName=FinalConstants.PATH_DBPROP;
//使用java.util.Properties读取信息,Properties extends Hash
private static Properties prop=new Properties();
//设置默认的信息值
/*
*SQL Server 2000 连接数据库的相关字符串
*private static String dbClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver";
private static String dbUrl="jdbc:microsoft:sqlserver://localhost:1433;Database=AYAYA";
private static String dbUsr="sa";
private static String dbPwd="";
**/
private static String dbClassName="sun.jdbc.odbc.JdbcOdbcDriver";
private static String dbUrl="jdbc.odbc.electricDB";
private static String dbUsr="";
private static String dbPwd="";
//读取信息操作
private static void loadProperty()
{
try
{
prop.load(new FileInputStream(propFileName));
/*Searches for the property with the specified key in this
property list. If the key is not found in this property list,
the default property list, and its defaults, recursively,
are then checked. The method returns the default value
argument if the property is not found. */
dbClassName=prop.getProperty("DB_CLASS_NAME",
"sun.jdbc.odbc.JdbcOdbcDriver");
dbUrl=prop.getProperty("DB_URL","jdbc:odbc:electricDB");
dbUsr=prop.getProperty("DB_USR","");
dbPwd=prop.getProperty("DB_PWD","");
}
catch(Exception e)
{
e.printStackTrace();
}
}
//动态的加载类文件,获取一个连接
public static Connection getConnection()
{
Connection con=null;
loadProperty();
try
{
Class.forName(dbClassName);
con=DriverManager.getConnection(dbUrl,dbUsr,dbPwd);
}
catch(Exception ee)
{
ee.printStackTrace();
}
//当获取的连接是null,报告异常信息
if(con==null)
{
System.out.println("警告:DbConnectionManager.getConnection()获得数据库连接失败.\r\n\r\n连接类型:"+
dbClassName+"\r\n连接位置:"+dbUrl+"\r\n用户/密码:"+dbUsr+"/"+dbPwd);
}
return con;
}
public static void main(String args[])
{
try
{
DbConnectionManager db=new DbConnectionManager();
Connection con=db.getConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from NEWS");
while(rs.next())
{
System.out.print(rs.getInt(1)+" ");
System.out.print(rs.getString(2)+" ");
System.out.print(rs.getString(3)+" ");
System.out.print(rs.getString(4)+" ");
System.out.print(rs.getString(5)+" ");
System.out.print(rs.getInt(6)+" ");
System.out.print(rs.getInt(7)+" ");
System.out.println("");
}
}
catch(SQLException se)
{
se.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -