
public class Demo {
public static void main(String agrs[]) {
Connection con = null
PreparedStatement pstmt = null
String sql = "delete from user where username=?"
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver") //设置数据库连接的驱动
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433databaseName=数据库") //设置数据库连接的 URL,用户名,密码
pstmt = con.prepareStatement(sql)
pstmt.setString(1, "aaa") // 设置SQL语句中username的值
int count = pstmt.executeUpdate()
if (count >0) {
System.out.println(" *** 作成功")
} else {
System.out.println(" *** 作失败")
}
} catch (Exception e) {
e.printStackTrace()
}
}
}
连接数据库public class DBManager {
//定义数据库连接的URL
private static final String URL="jdbc:sqlserver://localhost:1433database=j1105"
//定义数据库的用户名
private static final String USERNAME = "sa"
//定义数据库密码
private static final String PASSWORD = "sa"
//定义一个连接的引用,使用单例模式
private static Connection conn = null
//使用静态块来注册驱动
//类加载时自动执行代码块
static {
//反射com.microsoft.sqlserver.jdbc.SQLServerDriver.class
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
} catch (ClassNotFoundException e) {
e.printStackTrace()
}
}
//获得连接
//在程序使用过程中始终只有1个对象存在
//使用单例模式来给Connection赋值
public static Connection getConnection(){
if(conn == null){
try {
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD)
} catch (SQLException e) {
e.printStackTrace()
}
}
return conn
}
/**
* 关闭的一些 *** 作 , 优化
* @param conn
* @param stat
* @param rs
*/
public static void close(Connection conn,Statement stat,ResultSet rs){
try{
if(conn != null){
conn.close()
}
if(stat != null){
stat.close()
}
if(rs != null){
rs.close()
}
}catch(SQLException e){
e.printStackTrace()
}
}
/**
* 重写上面的方法,在只有2个参数的情况下关闭
* @param conn
* @param stat
*/
public static void close(Connection conn,Statement stat){
try{
if(conn != null){
conn.close()
}
if(stat != null){
stat.close()
}
}catch(SQLException e){
e.printStackTrace()
}
}
public static void main(String[] args){
Connection conn = DBManager .getConnection()
System.out.println(conn)
}
}
接口
public interface IStudentDao {
public void deleteStudent(int xh)
}
实现
public class StudentDAOimpl implements IStudentDao {
public void deleteStudent(int xh) {
try{
String sql = "delete from tb_student where xh = ?"
PreparedStatement ps = conn.prepareStatement(sql)
ps.setInt(1, xh)
ps.executeUpdate()
System.out.println("成功删除")
}catch(SQLException e){
e.printStackTrace()
}
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)