import java.sql.Connection
import java.sql.DriverManager
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException
import java.sql.Statement
public class Datebase{
public Connection conn=null
public Statement stmt=null
public ResultSet rs=null
public PreparedStatement preparedstmt=null
private static String dbDriver="com.mysql.jdbc.Driver"
private static String dbUrl="jdbc:mysql://localhost/graduatedmanager?useUnicode=true&characterEncoding=gb2312"
private static String dbUser="root"
private static String dbPwd="root"
//打开数据库连接
public Datebase(){}
public static Connection getConnection()
{
java.sql.Connection conn=null
try
{
Class.forName(dbDriver)
conn=DriverManager.getConnection(dbUrl,dbUser,dbPwd)
}
catch(Exception e)
{
e.printStackTrace()
}
if(conn==null)
{
System.err.println("警告:数据库连接失败!")
}
return conn
}
//读取结果集
public ResultSet doQuery(String sql)
{
try
{
conn=Datebase.getConnection()
stmt=((java.sql.Connection) conn).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY)
rs=stmt.executeQuery(sql)
}
catch(SQLException e)
{
e.printStackTrace()
}
return rs
}
//更新数据
public int Prepared_doUpdate(String sql,String parameters[])
{
int result=0
try
{
conn=Datebase.getConnection()
preparedstmt=conn.prepareStatement(sql)
/* for(int i=0i<parameters.lengthi++)
{
System.out.println(parameters[i])
}*/
if(parameters!=null)
{
for(int i=0i<parameters.lengthi++)
{
preparedstmt.setString(i+1,parameters[i])
}
}
result=preparedstmt.executeUpdate()
}
catch(SQLException e)
{
e.printStackTrace()
System.out.println(" *** 作失败")
result=0
}
return result
}
//更新数据
public int doUpdate(String sql)
{
int result=0
try
{
conn=Datebase.getConnection()
stmt=((java.sql.Connection) conn).createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY)
result=stmt.executeUpdate(sql)
}
catch(SQLException e)
{
result=0
}
return result
}
//关闭数据库连接
public void closeConnection()
{
try
{
if(rs!=null)
rs.close()
}
catch(Exception e)
{
e.printStackTrace()
}
try
{
if(conn!=null)
((Statement) conn).close()
}
catch(Exception e)
{
e.printStackTrace()
}
}
}
try{class.forName(driver)
}
catch (ClassNotFoundException e)
{
e.printStackTrace()
}
错了,应该写在方法里面。。。
public Connection getConnection()
{
try{
class.forName(driver)
connection = DriverManager.getConnection(URL,username,password)
}
catch (SQLException e1)
{
e1.printStackTrace()
}
catch (ClassNotFoundException e)
{
e.printStackTrace()
}
return connection
}
或者把他放在构造方法里。
当然是:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
编译肯定不对。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)