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()
}
}
}
java本身对数据库没有封装,对数据库封装好的有hibernate,ibatis(mybatis),hibernate封装的比较彻底,基本 *** 作不用自己写SQL语句,ibatis的话还是要自己写SQL语句,比较灵活.欢迎分享,转载请注明来源:内存溢出
评论列表(0条)