xlang v4.0 Release
程序设计语言基础库文档
载入中...
搜索中...
未找到
xsql.xcs
浏览该文件的文档.
1//xlang
2
3package Sql{
4 public class SqlException : Exception{
5 public SqlException(){
6
7 }
8 public SqlException(int err, String sqlmessage){
9 errcode = err;
11 }
12 };
13
14 public class DatabaseNotSupportException : SqlException{
16 errcode = 0;
17 message = "not support method:" + sqlmessage;
18 }
19 };
20
21 public interface ConnPoolCallback{
22 Connection createConnection();
23 bool alive(Connection conn);
24 };
25
26 public class ConnectionPool{
27 static class connectorMgr{
28 public Connection pconnection;
29 public long timestamp;
30 };
31
33 Map<int, bool> _error_map = new Map<int, bool>();
34
35 static const int TIMEOU_LIMIT = 300000;
36
38 int _active_cnt, _wait_time;
39 int _validtesttime, _maxIdleTime, _maxIdle;
40
41 ConnPoolCallback callback;
42
43
44 Connection allocate(){
45 Connection connector = callback.createConnection();
46 if (connector != nilptr){
47 _active_cnt++;
48 }
49 return connector;
50 }
51
52 public Connection getConnector(){
53 Connection connector = nilptr;
54 long lastactive = 0;
55
56 synchronized(_pool){
57 if (_maxConnect != 0){
58 while ((_pool.size() == 0) && (_active_cnt >= _maxConnect)){
59 _pool.wait();
60 }
61 }
62
63 do{
64 if (connector != nilptr){
65 _active_cnt--;
66 connector.close();
68 }
69
70 lastactive = 0;
71
73 if (iter.hasNext()){
74 connectorMgr mgr = iter.get();
75 connector = mgr.pconnection;
76 lastactive = mgr.timestamp;
77 _pool.remove(iter);
78 }else{
79 break;
80 }
81
82 } while (test(connector, lastactive) == false);
83
84 if (connector == nilptr){
85 if ((_maxConnect == 0) || (_active_cnt < _maxConnect)){
86 connector = allocate();
87 }
88 }
89 }
90 return connector;
91 }
92
93 bool test(Connection conn, long lastactive){
94 if ( (_system_.currentTimeMillis() - lastactive) > _validtesttime){
95 return callback.alive(conn);
96 }
97 return true;
98 }
99
100 public void recycle(Connection connection){
101
102 int mysql_error = connection.getErrorCode();
103
104 if (_error_map.containsKey(mysql_error) == false){
105 synchronized(_pool){
109
110 if (_maxIdleTime != 0){
112
113 while (it != nilptr && it.hasNext()){
114 List.Iterator<connectorMgr> tmp = it.getNext();
116
117 if ((mgr.timestamp - pmt.timestamp) > _maxIdleTime){
118 pmt.pconnection.close();
119 _pool.remove(it);
120 _active_cnt--;
121 }
122 it = tmp;
123 }
124 }
125
126
127
128 if (_maxIdle != 0){
129 while (_pool.size() > _maxIdle){
131 connectorMgr pmt = tmp.get();
132 pmt.pconnection.close();
133 _pool.remove(tmp);
134 _active_cnt--;
135 }
136 }
137 _pool.add(mgr);
138 _pool.notify();
139 }
140 } else{
141 connection.close();
142 synchronized(_pool){
143 _active_cnt--;
144 }
145 }
146 }
147
159 public bool config(ConnPoolCallback _callback, String reset_error, int maxWait, int maxConnect, int maxIdle, int maxIdleTime, int validtesttime){
160
161 if (maxIdle != 0 && maxConnect != 0 && maxIdle >= maxConnect){
162 throw new IllegalArgumentException("Connector config failed : maxIdle >= maxConnect\n");
163 return false;
164 }
165
166 if (_callback == nilptr){
167 return false;
168 }
169
170 callback = _callback;
171
172 _validtesttime = validtesttime;
173
174 if (reset_error != nilptr){
176 String[] elist = err_list.split(',');
177 for (int i = 0; i < elist.length; i++){
178 String str = elist[i];
179 str.trim(true);
180 _error_map.put(str.parseInt(), true);
181 }
182 }
183
184 if (maxWait != -1){
185 _wait_time = maxWait;
186 }
187
188 _maxIdle = maxIdle;
189 _maxConnect = maxConnect;
190 _maxIdleTime = maxIdleTime;
191 return true;
192 }
193
194 public void clear(){
195 synchronized(_pool){
196 _pool.clear();
197 _error_map.clear();
198 _wait_time = 0;
199 _maxConnect = 0;
200 _maxIdle = 0;
201 _active_cnt = 0;
202 _maxIdleTime = TIMEOU_LIMIT;
203 }
204 }
205 };
206
207 public class Database{
209
210 public static bool reigstry(String name, ConnectionRegister reg){
211 synchronized(_database){
212 if (_database.containsKey(name) == false){
213 _database.put(name, reg);
214 return true;
215 }
216 }
217 return false;
218 }
219
220 public static Connection getConnection(String driverName){
221 synchronized(_database){
222 try{
223 ConnectionRegister cr = _database.get(driverName);
224 return cr.allocConnection(driverName);
225 }catch(Exception e){
226
227 }
228 }
229 return nilptr;
230 }
231
232
233 };
234
235 public interface ConnectionRegister{
237 };
238
239 public interface Connection{
244 void create(String uri, String username, String pwd);
245
250 void setOption(int opt, Object option);
251
253
254 PreparedStatement prepareStatement(String sql);
255
256 Statement createStatement();
257
259
261
262 bool isClosed();
263
264 void close();
265 };
266
267
300
301 public interface Statement{
302 int execute(String sql);
303
304 ResultSet executeQuery(String sql);
305
307
308 ResultSet getResult();
309
310 void close();
311
313 };
314
315 public static class PreparedStatement : Statement{
316
320 int paramid = 0;
323 textSql = " " + sql + " ";
324 strsplit = textSql.split('?');
325 if (strsplit.length == 0){
326 throw new IllegalArgumentException("invalid sql");
327 }
328 strparams = new String[strsplit.length - 1];
329 }
330
331 public String safety(String str){
332 str = str.replace("\\", "\\\\");
333 str = str.replace("\"", "\\\"");
334 str = str.replace("\'", "\\\'");
335 str = str.replace("\`", "\\\`");
336 return "'" + str + "'";
337 }
338
339 public int execute(){
340 return execute(getSql());
341 }
342
343 public String getSql(){
344 String sqlout = strsplit[0];
345 int i = 1, c = strsplit.length;
346 for (; i < c; i++){
347 sqlout = sqlout + (strparams[i - 1] + strsplit[i]);
348 }
349 return sqlout;
350 }
351
352 public ResultSet executeQuery(){
353 return executeQuery(getSql());
354 }
355
356 public int executeUpdate(){
357 return executeUpdate(getSql());
358 }
359
360 public void setValue(String value){
361 if (paramid < strparams.length){
362 strparams[paramid++] = safety(value);
363 }else{
364 throw new SqlException(-1, "sql " +textSql + " dont need value:" + value);
365 }
366 }
367
368 public void setValue(int value){
369 if (paramid < strparams.length){
370 strparams[paramid++] = String.format("%d",value);
371 }else{
372 throw new SqlException(-1, "sql " +textSql + " dont need value:" + value);
373 }
374 }
375
376 public void setValue(long value){
377 if (paramid < strparams.length){
378 strparams[paramid++] = String.format("%d",value);
379 }else{
380 throw new SqlException(-1, "sql " +textSql + " dont need value:" + value);
381 }
382 }
383
384 public void setValue(byte value){
385 if (paramid < strparams.length){
386 strparams[paramid++] = String.format("%02u",value & 0xff);
387 }else{
388 throw new SqlException(-1, "sql " +textSql + " dont need value:" + value);
389 }
390 }
391
392 public void setValue(double value){
393 if (paramid < strparams.length){
394 strparams[paramid++] = String.format("%f",value);
395 }else{
396 throw new SqlException(-1, "sql " +textSql + " dont need value:" + value);
397 }
398 }
399
400
401 public void setValue(int id, String value){
402 if ((id > 0) && (id - 1 < strparams.length)){
403 strparams[id - 1] = safety(value);
404 }else{
405 throw new SqlException(-1, "sql " +textSql + " dont need value:" + value);
406 }
407 }
408
409 public void setValue(int id, int value){
410 if ((id > 0) && (id - 1 < strparams.length)){
411 strparams[id - 1] = String.format("%d",value);
412 }else{
413 throw new SqlException(-1, "sql " +textSql + " dont need value:" + value);
414 }
415 }
416
417 public void setValue(int id, long value){
418 if ((id > 0) && (id - 1 < strparams.length)){
419 strparams[id - 1] = String.format("%d",value);
420 }else{
421 throw new SqlException(-1, "sql " +textSql + " dont need value:" + value);
422 }
423 }
424
425 public void setValue(int id, byte value){
426 if ((id > 0) && (id - 1 < strparams.length)){
427 strparams[id - 1] = String.format("%02u",value & 0xff);
428 }else{
429 throw new SqlException(-1, "sql " +textSql + " dont need value:" + value);
430 }
431 }
432
433 public void setValue(int id, double value){
434 if ((id > 0) && (id - 1 < strparams.length)){
435 strparams[id - 1] = String.format("%f",value);
436 }else{
437 throw new SqlException(-1, "sql " +textSql + " dont need value:" + value);
438 }
439 }
440
441 public void setValues(Object [] args){
442 for (int i = 0; i < args.length; i++){
443 if (args[i].instanceOf(String)){
444 setValue((String)args[i]);
445 }else
446 if (args[i].instanceOf(int)){
447 setValue((int)args[i]);
448 }else
449 if (args[i].instanceOf(long)){
450 setValue((long)args[i]);
451 }else
452 if (args[i].instanceOf(byte)){
453 setValue((byte)args[i]);
454 }else
455 if (args[i].instanceOf(double)){
456 setValue((double)args[i]);
457 }else{
458 throw new SqlException(-1, "sql " +textSql + " dont accept type:" + i);
459 }
460 }
461 }
462
463 public int get_changes()override{
464 throw new SqlException(-1, "get_changes");
465 return 0;
466 }
467
468 public void finalize(){
469 close();
470 }
471 };
472};
473
474
475/*
476
477void testSql1(){
478 Sql.ConnectionPool pool = new Sql.ConnectionPool();
479 pool.config(new Sql.ConnPoolCallback(){
480
481 Sql.Connection createConnection()override{
482 //TODO
483 Sql.Connection conn = Sql.Database.getConnection("sqlserver");
484 if (conn != nilptr){
485 conn.create("192.168.10.128", "sa", "233276111");
486 }
487 return conn;
488 }
489
490 bool alive(Sql.Connection conn)override{
491 //TODO
492 Sql.Statement state = conn.createStatement();
493 try{
494 state.execute("select 1;");
495 return true;
496 }catch(Exception e){
497
498 }
499 return false;
500 }
501 },"2006,2014",50, 50, 3, 300000, 10000);
502
503 for (int i = 0; i < 30; i++){
504 new Thread(){
505 void run()override{
506 testSqlite(pool);
507 }
508 }.start();
509 }
510}
511
512int testSqlite(Sql.ConnectionPool pool){
513
514 Sqlite.registry();
515
516 _system_.createConsole();
517
518 long before = _system_.currentTimeMillis();
519
520 for (int cx = 0; cx < 100;cx ++){
521 Sql.Connection slite = pool.getConnector();
522
523 if (slite != nilptr){
524
525 //slite.create("sqlite.db", nilptr, nilptr);
526 //slite.create("127.0.0.1", "root", "233276111");
527
528 //slite.setOption(Mysql.MysqlOption.CHARSET,"utf8");
529
530 //slite.setOption(Mysql.MysqlOption.SELECTDB, "test");
531
532
533 // 创建表
534 Sql.PreparedStatement stmt = slite.prepareStatement("CREATE table member(name varchar(32),age int) CHARSET=utf8");
535
536 //_system_.consoleWrite("time:" + (_system_.currentTimeMillis() - before) + " - 1\n");
537
538 try{
539 stmt.execute();
540 }catch(Exception e){
541 //_system_.consoleWrite("SqlException:" + e.getErrorCode() + "," + e.getMessage() + "\n");
542 }
543
544 String [] names = {
545 "嘉懿","煜城","懿轩","烨伟","苑博","伟泽","熠彤","鸿煊","博涛","烨霖","烨华","煜祺","智宸","正豪",
546 "昊然","明杰","立诚","立轩","立辉","峻熙","弘文","熠彤","鸿煊","烨霖","哲瀚","鑫鹏","致远","俊驰"
547 };
548
549 _system_.consoleWrite("time:" + (_system_.currentTimeMillis() - before) + " - before insert\n");
550
551 try{
552 //插入人名 年龄随机
553
554 for(int i = 0, c = names.length; i < c; i ++){
555 stmt = slite.prepareStatement("insert into member (name,age)VALUES(?, ?)");
556 stmt.setValue(names[i]);
557 stmt.setValue((int)(Math.random() * 80));
558 stmt.execute();
559 }
560 }catch(Exception e){
561 _system_.consoleWrite(e.getMessage() + "\n");
562 }
563 _system_.consoleWrite("time:" + (_system_.currentTimeMillis() - before) + " - after insert\n");
564
565
566 stmt = slite.prepareStatement("select * from member where age < ? limit 10");
567 stmt.setValue(40);
568
569 try{
570 Sql.ResultSet rs = stmt.executeQuery();
571 int c = rs.getRowCount();
572 while (rs.next()){
573 //_system_.consoleWrite(new String(rs.getString("name").getBytes("GB18030//IGNORE")) + ":" + rs.getString("age") + "\n");
574 }
575 }catch(Exception e){
576 _system_.consoleWrite(e.getMessage() + "\n");
577 }
578 }
579 pool.recycle(slite);
580 }
581
582 _system_.consoleWrite("done time:" + (_system_.currentTimeMillis() - before) + " - 4\n");
583
584 Thread.sleep(100);
585
586 return 0;
587}
588
589
590
591void testSql(){
592 //SqlServer.registry();
593
594 Sql.ConnectionPool pool = new Sql.ConnectionPool();
595 pool.config(new Sql.ConnPoolCallback(){
596
597 Sql.Connection createConnection()override{
598 //TODO
599 Sql.Connection conn = Sql.Database.getConnection("sqlserver");
600 if (conn != nilptr){
601 conn.create("192.168.10.128", "sa", "233276111");
602 }
603 return conn;
604 }
605
606 bool alive(Sql.Connection conn)override{
607 //TODO
608 Sql.Statement state = conn.createStatement();
609 try{
610 state.execute("select 1;");
611 return true;
612 }catch(Exception e){
613
614 }
615 return false;
616 }
617 },"2006,2014",50, 50, 3, 300000, 10000);
618
619 for (int i = 0; i < 30; i++){
620 new Thread(){
621 void run()override{
622 testSqlserver(pool);
623 }
624 }.start();
625 }
626}
627
628int testSqlserver(Sql.ConnectionPool pool){
629 _system_.createConsole();
630
631 for (int aa = 0;aa < 1000; aa++){
632 long before = _system_.currentTimeMillis();
633
634 Sql.Connection slite = pool.getConnector();
635 if (slite != nilptr){
636 Sql.PreparedStatement stmt = slite.prepareStatement("CREATE table blog..member(name varchar(32),age int)");
637
638 _system_.consoleWrite("time:" + (_system_.currentTimeMillis() - before) + " - 1\n");
639
640 try{
641 stmt.execute();
642 }catch(Exception e){
643 _system_.consoleWrite("SqlException:" + e.getErrorCode() + "," + new String(e.getMessage().getBytes("GB18030//IGNORE")) + "\n");
644 }
645
646 String [] names = {
647 "嘉懿","煜城","懿轩","烨伟","苑博","伟泽","熠彤","鸿煊","博涛","烨霖","烨华","煜祺","智宸","正豪",
648 "昊然","明杰","立诚","立轩","立辉","峻熙","弘文","熠彤","鸿煊","烨霖","哲瀚","鑫鹏","致远","俊驰"
649 };
650
651 _system_.consoleWrite("time:" + (_system_.currentTimeMillis() - before) + " - before insert\n");
652
653 try{
654 //插入人名 年龄随机
655
656 for(int i = 0, c = names.length; i < c; i ++){
657 stmt = slite.prepareStatement("insert into blog..member (name,age)VALUES(?, ?)");
658 stmt.setValue(names[i]);
659 stmt.setValue((int)(Math.random() * 80));
660 stmt.execute();
661 }
662 }catch(Exception e){
663 _system_.consoleWrite(new String(e.getMessage().getBytes("GB18030//IGNORE")) + "\n");
664 }
665 _system_.consoleWrite("time:" + (_system_.currentTimeMillis() - before) + " - after insert\n");
666
667
668 stmt = slite.prepareStatement("select top 10 * from blog..member where age < ?");
669 stmt.setValue(40);
670
671 try{
672 Sql.ResultSet rs = stmt.executeQuery();
673 int c = rs.getRowCount();
674 while (rs.isEof() == false){
675 _system_.consoleWrite(new String(rs.getString("name").getBytes("GB18030//IGNORE")) + ":" + rs.getString("age") + "\n");
676 rs.next();
677 }
678 }catch(Exception e){
679 _system_.consoleWrite(new String(e.getMessage().getBytes("GB18030//IGNORE")) + "\n");
680 }
681 pool.recycle(slite);
682 }
683 _system_.consoleWrite("done time:" + (_system_.currentTimeMillis() - before) + " - 4\n");
684 }
685
686 Thread.sleep(100);
687 return 0;
688}
689
690int main(String [] args){
691 testSql();
692 Thread.sleep(-1);
693 return 0;
694}
695*/
系统和IO相关
static final long currentTimeMillis()
异常类
map的迭代器对象
Definition List.xcs:11
_V get()
获取当前的值对象
void List()
Iterator iterator()
void clear()
void remove(Iterator)
int size()
void add(T)
bool get(K)
bool containsKey(K)
Iterator put(K, V)
void clear()
void recycle(Connection connection)
Definition xsql.xcs:100
ConnPoolCallback callback
Definition xsql.xcs:41
bool config(ConnPoolCallback _callback, String reset_error, int maxWait, int maxConnect, int maxIdle, int maxIdleTime, int validtesttime)
Definition xsql.xcs:159
Connection allocate()
Definition xsql.xcs:44
Connection getConnector()
Definition xsql.xcs:52
bool test(Connection conn, long lastactive)
Definition xsql.xcs:93
static bool reigstry(String name, ConnectionRegister reg)
Definition xsql.xcs:210
static Connection getConnection(String driverName)
Definition xsql.xcs:220
DatabaseNotSupportException(String sqlmessage)
Definition xsql.xcs:15
int get_changes() override
Definition xsql.xcs:463
void setValue(double value)
Definition xsql.xcs:392
void setValue(byte value)
Definition xsql.xcs:384
void setValue(int value)
Definition xsql.xcs:368
void setValue(int id, String value)
Definition xsql.xcs:401
PreparedStatement(String sql)
Definition xsql.xcs:322
void setValue(String value)
Definition xsql.xcs:360
String safety(String str)
Definition xsql.xcs:331
void setValue(int id, double value)
Definition xsql.xcs:433
void setValue(int id, int value)
Definition xsql.xcs:409
void setValue(int id, byte value)
Definition xsql.xcs:425
String [] strsplit
Definition xsql.xcs:318
String [] strparams
Definition xsql.xcs:319
void setValues(Object [] args)
Definition xsql.xcs:441
ResultSet executeQuery()
Definition xsql.xcs:352
void setValue(long value)
Definition xsql.xcs:376
void setValue(int id, long value)
Definition xsql.xcs:417
字符串类
int length()
static final String format(String, Object[])
String replace(int, int, String)
String trim(bool)
String [] split(String)
Connection createConnection()
bool alive(Connection conn)
void setOption(int opt, Object option)
String getError()
PreparedStatement prepareStatement(String sql)
Object getOption(int opt)
int getErrorCode()
void create(String uri, String username, String pwd)
Statement createStatement()
Connection allocConnection(String drivername)
bool previous()
double getDouble(int columnIndex)
String getString(int columnIndex)
int getColumnCount()
String getString(String columnlabel)
int getInt(int columnIndex)
bool getBoolean(String columnlabel)
int getInt(String columnlabel)
long getRowCount()
long getLong(String columnlabel)
long getLong(int columnIndex)
bool isFirst()
byte getByte(int columnIndex)
String getColumnName(int i)
byte getByte(String columnlabel)
double getDouble(String columnlabel)
int findColumn(String)
bool getBoolean(int columnIndex)
bool isValid()
int execute(String sql)
int executeUpdate(String sql)
ResultSet executeQuery(String sql)
ResultSet getResult()
int get_changes()