如题,我需要用Java来连接MySQL数据库,但是这个数据库实在别的服务器上,地址是: 208.81.166.169 ,现在我需要连接该数据库,假定用户名是:hythzxSQL,密码:727799796,请问该如何写呢?下面是我写的片段,我是初学者,请多包涵。try
{
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e2){}
try
{
//Connection con = DriverManager.getConnection("jdbc:odbc:mail");
Connection con = DriverManager.getConnection("jdbc:mysql://208.81.166.169:3306/hythzxSQL","hythzxSQL","727799796");
Statement stmt = con.createStatement();
String sql = "SELECT user,password FROM log";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next())
{
name=rs.getString("user");
password=rs.getString("password");
boolean name_password1=tf1.getText().equals(name);
boolean name_password2=tf2.getText().equals(password);
if(name_password1==true &&name_password2==true)
{
System.out.println("登录成功!");
}
else
{
System.out.println("用户名或密码错误!");
}
}
rs.close();
stmt.close();
con.close();
}
catch(Exception e3){}
{
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e2){}
try
{
//Connection con = DriverManager.getConnection("jdbc:odbc:mail");
Connection con = DriverManager.getConnection("jdbc:mysql://208.81.166.169:3306/hythzxSQL","hythzxSQL","727799796");
Statement stmt = con.createStatement();
String sql = "SELECT user,password FROM log";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next())
{
name=rs.getString("user");
password=rs.getString("password");
boolean name_password1=tf1.getText().equals(name);
boolean name_password2=tf2.getText().equals(password);
if(name_password1==true &&name_password2==true)
{
System.out.println("登录成功!");
}
else
{
System.out.println("用户名或密码错误!");
}
}
rs.close();
stmt.close();
con.close();
}
catch(Exception e3){}
一般关闭资源的语句,都放在finally里比较好。
这个位置上要写数据库名。
对的,地址是:208.81.166.169(网上的免费空间,10M MySQL数据库),数据库名是:hythzxSQL,用户名是:hythzxSQL,密码是:727799796。里面有两个简单的表,分别是log和remember
catch(Exception e3){
e3.printStackTrace();
}看看运行的时候报什么异常信息来着。
System.out.println("无法连接服务器!");
}
然后都是跳出来“无法连接服务器”
是这样的,我想写一个登录页面的程序,将这个程序的用户名和密码存放在数据库里,登陆时会检查数据库,我现在想把这个数据库放在网络上以便其他电脑访问,这个里面的user、password都是随便定的,并没有什么特殊含义。
嗯,错误是这个:
java.sql.SQLException: No suitable driver found for jdbc:mysql://208.81.166.169:3306/hythzxsql
请问是什么问题呢?应该是驱动的问题吧,怎么解决呢?
文件名类似于:
mysql-connector-java-xxx-bin.jar
这个文件要放到项目构建路径中来(也就是classpath中)。