One way of connecting to a database is through the JDBC driver manager using the method DriverManager.getConnection. This method uses a string containing a URL. The following is an example of using the JDBC driver manager to connect to Microsoft SQL Server 2000 while passing the user name and password: Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); Connection conn = DriverManager.getConnection ("jdbc:microsoft:sqlserver://server1:1433;User=test;Password=secret");
package test;
import java.sql.*;
try
{
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
Connection Conn = DriverManager.getConnection("jdbc:mysql://localhost/oa?user=root&password=&useUnicode=true&characterEncoding=8859_1");}
catch(ClassNotFoundException e){
System.out.println("Driver not found.");
System.out.println(e.toString());
throw new UnavailableException(this,"Class not found.");
}
catch(SQLException e)
{
System.out.println("An error occurs.");
System.out.println(e.toString());
throw new UnavailableException(this,"Cannot connect with the specified database.");
}public bbsreg() {
try {
Class.forName(sDBDriver);
}
catch(java.lang.ClassNotFoundException e) {
System.err.println("bbsreg(): " + e.getMessage());
}
}public ResultSet executeQuery(String sql) {
rs = null;
try {
conn = DriverManager.getConnection(sConnStr);
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
}
catch(SQLException ex) {
System.err.println("aq.executeQuery: " + ex.getMessage());
System.err.println("aq.executeQuerystrSQL: " + sql);
}
return rs;
}
public void executeUpdate(String sql) {
try {
conn = DriverManager.getConnection(sConnStr);
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql);
}
catch(SQLException ex) {
System.err.println("aq.executeUpdate: " + ex.getMessage());
System.err.println("aq.executeUpadatestrSQL: " + sql);
}
}}
这个样子:
可是编译时出错:
'class' or 'interface' expected
try
~
Connection conn = DriverManager.getConnection
("jdbc:microsoft:sqlserver://server1:1433;User=test;Password=secret");
数据库url连接好
应该没有什么问题了。。mysql没有连接过
http://www.chinajavaworld.net/doc/jdbc/
import java.sql.*;
try
{
你拷贝错代码了吧?
不是吧?可以这样写代码吗?
class 呢? interface 呢?
String sConnStr = "jdbc:mysql://localhost/oa?user=root&password=&useUnicode=true&characterEncoding=8859_1";
就可以了!