您的位置:首页 > 编程语言 > Java开发

Java 数据库操作

2011-11-27 09:57 225 查看
package SQLAction;
import java.sql.*;
import java.util.*;
public class Mysql {

private  static Connection conn;
private static  java.sql.PreparedStatement stmtdel;
public static void  connect() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/bbs";

conn = DriverManager.getConnection(url,"root","");
stmtdel = conn.prepareStatement("delete from news where id=?");

}
public static void showAll() throws Exception
{
String sql = "select * from news";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(sql);
System.out.print("---- id ---- title ---- content ----\n");
while(result.next())
{

System.out.print("|   "+result.getString("id")+"|   "+result.getString("title")+"|   "+result.getString("content")+"    |");
System.out.println();
}
}

public static void delete(int i ) throws Exception
{
stmtdel.setInt(1,i);
System.out.println(stmtdel.executeUpdate());

}
public static void deleteAll(int array[]) throws Exception   //执行多个删除处理  		addBatch
{
for(int i =0;i<array.length;i++)
{
stmtdel.setInt(1,array[i]);
stmtdel.addBatch();
}
int result[]=stmtdel.executeBatch();
System.out.println(Arrays.toString(result));
}
public static void main(String args[])throws Exception
{
connect();
System.out.println("删除前:");
showAll();
System.out.println("删除后:");
int array[] = {19,23,25,29,30,31,35};
deleteAll(array);
showAll();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: