下面的是几种常见数据库系统的数据库连接方式
系统环境:win2003 + j2se5.0 + tomcat5.5.7
前提是你已经从网上已经下载了各个数据库的JDBC支持!
把那些主要的工具包都放到Tomcat 5.5\common\lib就行!
刨除那些入门的东西吧,现在开始步入正题!
为了减少篇幅,更为了把问题说的直观,我已经把异常捕捉代码给去除了!
1.Microsoft SQL Server 2000
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection conn= DriverManager.getConnection
("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=数据库名字","sa","pwd");
Statement stmt=conn.createStatement();
//增加和查询语句
stmt.executeUpdate("insert into boya values('mssql','2000')");
ResultSet rs=statement.executeQuery("select * from boya");
//显示记录
while(rs.next()){
out.print(rs.getString(1)+" "+rs.getString(2));
out.println("<br>");
}
2.MySQL 5.0
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost/数据库名字?user=root&password=pwd");
Statement stmt=conn.createStatement();
//增加和查询语句
stmt.executeUpdate("insert into boya values('mysql','5.0')");
ResultSet rs=stmt.executeQuery("select * from boya");
//显示记录
while(rs.next()){
out.print(rs.getString(1)+" "+rs.getString(2));
out.println("<br>");
}
3.PostgreSQL 8.0
//这个服务器的默认端口5432,如果更改了,代码也需要更改
Class.forName("org.postgresql.Driver");
Connection conn=DriverManager.getConnection
("jdbc:postgresql://localhost:5432/数据库名字?user=admin&&password=pwd");
Statement stmt=conn.createStatement();
//增加和查询语句
stmt.executeUpdate("insert into boya values('mysql','5.0')");
ResultSet rs=stmt.executeQuery("select * from boya");
//显示记录
while(rs.next()){
out.print(rs.getString(1)+" "+rs.getString(2));
out.println("<br>");
}
4.ODBC
//in my opinion 会写ODBC就够了,现在PostgreSQL、MYSQL里也都有ODBC支持,但速度慢啊!
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:test","","");
Statement stmt=conn.createStatement();
//增加和查询语句
stmt.executeUpdate("insert into boya values('mysql','5.0')");
ResultSet rs=stmt.executeQuery("select * from boya");
//显示记录
while(rs.next()){
out.print(rs.getString(1)+" "+rs.getString(2));
out.println("<br>");
}