windows 操作系统中:控制面板->管理工具->数据源(ODBC)->用户DSN,添加数据源,选择SQL server驱程...
//javaBean:给你一个例子:
package ch02.bookshop;
import java.sql.*;
import java.util.*;
public class BookModel
{
private Connection con;
private static String str;
public static Connection getConnection()
{
Connection con=null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//先加载JdbcOdbcDriver
con=DriverManager.getConnection("jdbc:odbc:BookLibrary");//建立和数据库的连接
}
catch(Exception e)
{
e.printStackTrace();
}
return con;
}
public BookModel()
{
this.con=BookModel.getConnection();
}
public Collection getAllBook()throws Exception
{
Statement stmt=con.createStatement();//建立Statement
ResultSet rst=stmt.executeQuery("select * from Book");//执行sql语句返回ResultSet
Collection ret=new ArrayList();
while(rst.next())
{
BookObject temp=new BookObject();
temp.setBookId(rst.getString("BookId"));
temp.setBookName(rst.getString("BookName"));
temp.setPublisher(rst.getString("Publisher"));
temp.setPrice(rst.getFloat("Price"));
ret.add(temp);
}
con.close();
return ret;
}
public void addBook(BookObject book)throws Exception
{
String bookId=book.getBookId();
String bookName=book.getBookName();
String publisher=book.getPublisher();
float price=book.getPrice();
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into Book values('"+bookId+"','"+bookName+"','"+publisher+"','"+price+"')");
}
public void deleteBook(String bookId) throws Exception
{
Statement stmt=con.createStatement();
stmt.execute("delete from Book where BookId='"+bookId+"'");
}
public BookObject getBookInfo(String bookId) throws Exception
{
Statement stmt=con.createStatement();
str=bookId;
ResultSet rst=stmt.executeQuery("select * from Book where BookId='"+bookId+"'");
BookObject book=null;
while(rst.next())
{
book=new BookObject();
book.setBookId(rst.getString("BookId"));
book.setBookName(rst.getString("BookName"));
book.setPublisher(rst.getString("Publisher"));
book.setPrice(rst.getFloat("Price"));
}
rst.close();
stmt.close();
return book;
}
public void modifyBook(BookObject book) throws Exception
{
String bookId=book.getBookId();
String bookName=book.getBookName();
String publisher=book.getPublisher();
float price=book.getPrice();
Statement stmt=con.createStatement();
stmt.execute("update Book set BookId='"+bookId+"',BookName='"+bookName+"',Publisher='"+publisher+"',Price='"+price+"' where BookId='"+str+"'");
}
}