一个连接mysql的javaBean,请高手指点,为什么老是连不上?是否连接串有问题!?
aoplo 2004-08-03 05:10:42 /*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package connDB;
import java.sql.*;
/**
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class Connmysql
{
private String sample = "Sample";
private String m_ErrMsg;
private Connection conn;
private Statement st;
private ResultSet rs;
public Connmysql()
{
InitDB();
}
public String getSample()
{
return sample;
}
public void setSample(String sample)
{
this.sample = sample;
}
public String getLastErrMsg()
{
return m_ErrMsg;
}
boolean InitDB()
{
m_ErrMsg="";
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection StrConn = DriverManager.getConnection("jdbc:mysql://jsp2/bohan?user=root&password=&useUnicode=true&characterEncoding=GB2312");
st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
}
catch (Exception ex)
{
m_ErrMsg=ex.getMessage();
return false;
}//end try-catch
return true;
}
public ResultSet executeQuery(String strsql)
{
m_ErrMsg="";
System.out.println(strsql);
try
{
System.out.println("SQL执行....开始");
//st.execute(strsql);
rs = st.executeQuery(strsql);
System.out.println("SQL执行....成功结束");
}
catch(SQLException ex)
{
System.out.println("SQLException");
System.out.print(strsql);
System.out.println("SQL执行....发生错误");
System.err.println(ex.getMessage());
m_ErrMsg=ex.getMessage();
return null;
}
catch (Exception ex)
{
System.out.println("Exception");
System.out.print(strsql);
System.out.println("SQL执行....发生错误");
System.err.println(ex.getMessage());
m_ErrMsg=ex.getMessage();
return null;
}
return rs;
}
public boolean UpdateSql(String strsql)
{
System.out.print(strsql);
m_ErrMsg="";
try{
st.executeUpdate(strsql);
}
catch(SQLException ex)
{
System.out.println("SQLException");
System.out.print(strsql);
System.out.println("SQL执行....发生错误");
System.err.println(ex.getMessage());
m_ErrMsg=ex.getMessage();
return false;
}
catch (Exception ex)
{
System.out.println("Exception");
System.out.print(strsql);
System.out.println("SQL执行....发生错误");
System.err.println(ex.getMessage());
m_ErrMsg=ex.getMessage();
return false;
}
return true;
}
public static void main(String[] args) {
Connmysql db = new Connmysql();
ResultSet rs = db.executeQuery("select * from test");
if (rs == null)
{
return;
}
try
{
while (rs.next())
{
System.out.println(rs.getString(1));
}
rs.close();
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
}