用java如何实现 BS的分布式数据库

用java如何实现 BS的分布式数据库,第1张

B/S与分布式无关

在B端只知道一个网站,与S端的具体实现也无关

在S端的后面可以有多种方式存取数据,但如果自己用java来实现这多种方式,将会是非常麻烦的事情,所以一般情况下用第三方的数据访问接口,这样对于S端来说,只有一个接口存取数据

在这第三方数据接口的后面才是数据存贮层,这里就可以有多种方式的数据部署形式,比如分布式等等。

所以我们编程的 S端使用何种语言 都与 分布式无关。

链接数据库代码最好封装成一个类,不然到处都写的是连接数据库的代码,用数据源链接数据库,代码如下:package DesignerFamilyAccountMoneycomm;import javaioIOException;

import javaioInputStream;

import javasqlConnection;

import javasqlPreparedStatement;

import javasqlResultSet;

import javasqlSQLException;

import javautilHashMap;

import javautilProperties;import javaxsqlDataSource;import orgapachecommonsdbcpBasicDataSource;import DesignerFamilyAccountMoneymainexceptionExceptionDemo;public class DBUtil {

private static final String driver;

private static final String url;

private static final String username;

private static final String password;

private static DataSource datasource;

private static HashMap<String,String> map; static {

Properties config = new Properties();

InputStream in = DBUtilclassgetResourceAsStream("configproperties");

try {

configload(in);

} catch (IOException e) {

throw new ExceptionDemo("装载配置文件出错",e);

}

driver = configgetProperty("jdbcdriver");

url = configgetProperty("jdbcurl");

username = configgetProperty("jdbcusername");

password = configgetProperty("jdbcpassword");

map = new HashMap<String, String>();

mapput("loginselectbynamepassword",configgetProperty("sqlloginselectbynamepassword"));

mapput("loginselectbyname",configgetProperty("sqlloginselectbyname"));

mapput("logininsert",configgetProperty("sqllogininsert"));

mapput("accountmoneyinsert",configgetProperty("sqlaccountmoneyinsert"));

mapput("accountmoneyselectall",configgetProperty("sqlaccountmoneyselectall"));

mapput("accountmoneydelete",configgetProperty("sqlaccountmoneydelete"));

mapput("accountmoneyselectByDate",configgetProperty("sqlaccountmoneyselectByDate"));

mapput("salaryselectall",configgetProperty("sqlsalaryselectall"));

mapput("salaryselectbyname",configgetProperty("sqlsalaryselectbyname"));

mapput("salarydelete",configgetProperty("sqlsalarydelete"));

mapput("salaryinsert",configgetProperty("sqlsalaryinsert"));

mapput("sortselectall",configgetProperty("sqlsortselectall"));

mapput("sortselectbyname",configgetProperty("sqlsortselectbyname"));

mapput("sortdelete",configgetProperty("sqlsortdelete"));

mapput("sortinsert",configgetProperty("sqlsortinsert"));

} public static DataSource getConnection() {

if(datasource==null){

BasicDataSource bds;

bds = new BasicDataSource();

bdssetDriverClassName(driver);

bdssetUrl(url);

bdssetUsername(username);

bdssetPassword(password);

datasource = bds;

}

return datasource; }

public static HashMap<String,String> getMap() {

return map;

} // 释放资源

public static void realse(ResultSet rst, PreparedStatement psd, Connection conn) {

try {

if (rst != null) {

rstclose();

}

} catch (SQLException e) {

eprintStackTrace();

} finally {

try {

if (psd != null)

psdclose();

} catch (SQLException e) {

eprintStackTrace();

} finally {

try {

if (conn != null)

connclose();

} catch (SQLException e) {

eprintStackTrace();

}

}

}

}

}

用法:例如判断用户名和密码:public static boolean Justice(String username, String password) {

try {

conn = dbsgetConnection();

psd = conn

prepareStatement(mapget("loginselectbynamepassword"));

psdsetString(1, username);

psdsetString(2, password);

rst = psdexecuteQuery();

flag = rstnext();

} catch (SQLException e) {

throw new ExceptionDemo("判断用户名和密码时出错", e);

} finally {

DBUtilrealse(rst, psd, conn);

}

if (flag) {

return true;

}

return false;

} 不过我给你的这个链接数据库要有配置文件,即:。property的文件:如下:jdbcdriver=sunjdbcodbcJdbcOdbcDriver

jdbcurl=jdbc:odbc:driver={Microsoft Access Driver (mdb)};DBQ=studmdb

jdbcusername=

jdbcpassword=

sqlloginselectbynamepassword=select user_name,pass_word from login where user_name= and pass_word=

sqlloginselectbyname=select username from login where username=

sqllogininsert=insert into login(username,sex,age,user_name,pass_word) values(,,,,) sqlaccountmoneyinsert=insert into account_money(in_out,sort_in_out,date_money,money_account,ps) values(,,,,)

sqlaccountmoneyselectall=select id,in_out,sort_in_out,date_money,money_account,ps from account_money

sqlaccountmoneyselectByDate=select id,in_out,sort_in_out,date_money,money_account,ps from account_money where date_money between and

sqlaccountmoneydelete=delete from account_money where id=

sqlsalaryselectall=select from salary

sqlsalaryselectbyname=select from salary where in_sort=

sqlsalarydelete=delete from salary where in_sort=

sqlsalaryinsert=insert into salary(in_sort) values()sqlsortselectall=select from sort

sqlsortselectbyname=select from sort where out_sort=

sqlsortdelete=delete from sort where out_sort=

sqlsortinsert=insert into sort(out_sort) values()不是很难,应该看的懂,上半部分是链接数据库必备条件,下面是执行的sql语句,在Dbutil里用静态代码快读出来。。这个是最底层的链接方式。。还有其他的第三方类库链接数据库。如:hibanate等等。。

package comhdjdbc;

import javaioIOException;

import javasqlConnection;

import javasqlPreparedStatement;

import javasqlResultSet;

import javasqlSQLException;

import javasqlStatement;

import javautilHashMap;

import javautilProperties;

import javaxnamingContext;

import javaxnamingInitialContext;

import javaxsqlDataSource;

import javaxsqlRowSet;

import sunjdbcrowsetCachedRowSet;

public class Orcalzx {

private static String urls,users,passwords;

static

{

/ Properties prop=new Properties();

urls="jdbc:mysql://localhost:3306/investuseUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false";

users="root";

passwords="123";

}

public static Connection getConnection() {

Connection con = null;

try {

//con = DriverManagergetConnection(url, user, password);

con=locateDs()getConnection(); //通过数据源得到连接

} catch (SQLException e) {

Systemoutprintln(etoString());

}

return con;

}

public static DataSource locateDs()

{

DataSource ds = null;

HashMap cachedDs = new HashMap();

if (cachedDscontainsKey("ds"))

ds = (DataSource)cachedDsget("ds");

else {

try {

//初始化上下文

Context initCtx = new InitialContext();

ds = (DataSource)initCtxlookup("java:comp/env/jdbc/ds"); //jdbc/ds是数据源名称

//ds = (DataSource)initCtxlookup("java:/ds"); //jboss数据源连接方式

cachedDsput("ds", ds);

} catch (Exception e) {

eprintStackTrace();

}

}

return ds;

}

public static RowSet query(String sql)

{

CachedRowSet crs=null;//需要选择sunjdbcrowsetCachedRowSet;

ResultSet rs=null;

Connection conn=getConnection();

try {

crs=new CachedRowSet();

Statement stmt=conncreateStatement();

rs=stmtexecuteQuery(sql);

crspopulate(rs);

} catch (SQLException e) {

eprintStackTrace();

}

finally{

try {

connclose();

} catch (SQLException e) {

eprintStackTrace();

}

}

return crs;

}

/public static boolean preupdate(String sql)

{

boolean f=true;

Connection conn=getConnection();

try {

PreparedStatement stmt=connprepareStatement(sql);

stmtsetInt(1, 6);

stmtsetString(2, "gfkg");

stmtsetString(3, "gflg");

//Systemoutprintln(stmtexecuteUpdate());

//stmtexecuteUpdate(sql);

} catch (SQLException e) {

f=false;

eprintStackTrace();

}

finally{

try {

connclose();

} catch (SQLException e) {

eprintStackTrace();

}

}

return f;

}/

public static boolean update(String sql)

{

boolean f=true;

Connection conn=getConnection();

try {

Statement stmt=conncreateStatement();

stmtexecuteUpdate(sql);

} catch (SQLException e) {

f=false;

//eprintStackTrace();

}

finally{

try {

connclose();

} catch (SQLException e) {

eprintStackTrace();

}

}

return f;

}

/ public static String select(String sql){

String pwd="";

try {

ResultSet rs=query(sql);//从 CachedRowSet 对象获取数据可使用继承自 ResultSet 接口的获取方法

while(rsnext())

{

//int id=rsgetInt(1); //列的索引

//user=rsgetString("username");

pwd=rsgetString("dept");

Systemoutprintln(pwd);

// Systemoutprintln(" /密码"+password);

}

} catch (SQLException e) {

eprintStackTrace();

}

return pwd;

}

public static void main(String[] args) {

// Systemoutprintln(OrcalzxgetConnection());

String sql="select from jtest where rownum<10";

try {

ResultSet rs=query(sql);//从 CachedRowSet 对象获取数据可使用继承自 ResultSet 接口的获取方法

while(rsnext())

{

//int id=rsgetInt(1); //列的索引

int id=rsgetInt("id");

user=rsgetString("username");

password=rsgetString("password");

Systemoutprintln("id:"+id+" /用户"+user+" /密码"+password);

}

} catch (SQLException e) {

eprintStackTrace();

}

String sql="select from users";

try {

ResultSet rs=query(sql);//从 CachedRowSet 对象获取数据可使用继承自 ResultSet 接口的获取方法

while(rsnext())

{

//int id=rsgetInt(1); //列的索引

user=rsgetString("username");

password=rsgetString("pwdhash");

Systemoutprintln(" /用户"+user+" /密码"+password);

}

} catch (SQLException e) {

eprintStackTrace();

}

String sql="select from (select rownum rid, t from employee t where rownum<=3)t where rid>0";

//query(sql);

ResultSet rs=query(sql);//从 CachedRowSet 对象获取数据可使用继承自 ResultSet 接口的获取方法

try {

while(rsnext())

{

//int id=rsgetInt(1); //列的索引

//user=rsgetString("username");

String pwd=rsgetString("FIRST_NAME");

Systemoutprintln(pwd);

//Systemoutprintln(" /密码"+password);

}

} catch (SQLException e) {

// TODO Auto-generated catch block

eprintStackTrace();

}

}/

}

希望你能看懂。很早以前写的。这里如何连接数据库 输出 怎么取值都有。记得采纳我的啊。

1增加\x0d\String s1="insert into tableNames (id,name,password) values(myseqnextval,,);"\x0d\ClassforName(driver);\x0d\Connection conn = DriverManagergetConnection(url,dbUser,dbPwd);\x0d\PreparedStatement prepStmt = connprepareStatement(s1);\x0d\prepStmtsetString(1,name);\x0d\prepStmtsetString(2,password);\x0d\ResultSet rs=stmtexecuteUpdate();\x0d\2、删除\x0d\String s2="delete from tbNames where name=";\x0d\ClassforName(driver);\x0d\Connection conn = DriverManagergetConnection(url,dbUser,dbPwd);\x0d\PreparedStatement prepStmt = connprepareStatement(s2);\x0d\prepStmtsetString(1,name);\x0d\ResultSet rs=stmtexecuteUpdate();\x0d\3、修改\x0d\String s3=“update tbNames set name= where id=”;\x0d\ClassforName(driver);\x0d\Connection conn = DriverManagergetConnection(url,dbUser,dbPwd);\x0d\PreparedStatement prepStmt = connprepareStatement(s3);\x0d\prepStmtsetString(1,name);\x0d\prepStmtsetString(2,id);\x0d\ResultSet rs=stmtexecuteUpdate();\x0d\4、查询\x0d\String s4="select id,name,password from tbNames";\x0d\ClassforName(driver);\x0d\Connection conn = DriverManagergetConnection(url,dbUser,dbPwd);\x0d\Statement stmt=conncreateStatement();\x0d\ResultSet rs = stmtexecuteQuery(s4);\x0d\while(rsnext){\x0d\int id=rsgetInt(1);\x0d\String name = rsgetString(2);\x0d\String pwd=rsgetString(3);\x0d\Systemoutprintln(id+name+pwd); } \x0d\\x0d\以上四步必须都得关闭连接;!!!\x0d\rsclose();\x0d\stmtclose();\x0d\connclose();

你要实现的这个可能跟SpringMvc的关系不是很大。

你要达到的目的其实就是在jvm启动的时候把数据库数据加载一份到内存,一个静态变量和一个静态初始化块就可以搞定你的问题,这两者都是在类加载的时候初始化一次,像前面回答的一样,你可以用一个HashMap搞定。稍微具体来说,一个静态变量

publicstaticfinalMapcache=newHashMap()

static{

cache=请求数据库 *** 作

}

key你自己加,String还是int都行,value是你数据库的结构,可以写个实体。获取的时候直接cacheget(key)就可以了。

java如何从数据库读取数据并写入txt文件:

将数据查询出来放在list中,然后写入文件。

给你个写入的类,查询数据自己如果能搞定最好了。

FileWriterfileWriter=newFileWriter("c:\Resulttxt");

int[]a=newint[]{11112,222,333,444,555,666};

for(inti=0;i

fileWriterwrite(StringvalueOf(a[i])"");

}

fileWriterflush();

fileWriterclose();

上面例子中的a也可以是list。

// *** 作acess的

package cnzhtech;

import javasql;

import javaio;

public class DBManager {

/

@param args

/

public static void main(String[] args) {

// TODO 自动生成方法存根

String strPath="";//当前程序根路径

try{

File f=new File("");

strPath=fgetCanonicalPath();

}catch(IOException e){

Systemoutprintln(etoString());

}

//access文件路径

String url="jdbc:odbc:Driver={MicroSoft Access Driver (mdb)};DBQ="+strPath+"\\data\\aamdb";

String username="";

String password="";

Connection con;

Statement stml;

ResultSet res;

try{

ClassforName("sunjdbcodbcJdbcOdbcDriver");//加载驱动

con=DriverManagergetConnection(url, username, password);//获取连接

stml=concreateStatement();//建立statement

res=stmlexecuteQuery("select from test");//查询

while(resnext()){//显示

Systemoutprintln(resgetString("u_name")+"\n");

}

resclose();

stmlexecuteUpdate("insert into test(u_name) values('kkk')");//插入

stmlexecuteUpdate("delete from test where u_ID=3");//删除

stmlexecuteUpdate("update test set u_name='mengkaide' where u_ID=4");//修改

stmlclose();//关闭

conclose();

}catch(Exception e){

Systemoutprintln(etoString());

}

}

}

以上就是关于用java如何实现 B/S的分布式数据库全部的内容,包括:用java如何实现 B/S的分布式数据库、JAVA中界面如何连接数据库,如何实现一个界面到另一个界面、用java方式实现与主流数据库mysql通信等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/sjk/9859713.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-02
下一篇2023-05-02

发表评论

登录后才能评论

评论列表(0条)

    保存