/**
*
*/
package ws;
import java.sql.*;
import printSqlException.PrintSqlException;
/**
* @author Stephen Wong
* @version 1.1
*/
public class MyOdbc {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String url="jdbc:microsoft:sqlserver://stephenewong:1433;databasename=pubs";
try
{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
/*部分接受键盘的代码
* System.out.println("user:");
int data;
int i=0;
byte[] buf= new byte[100];
while((data=System.in.read())!='q')
{
buf[i]=(byte)data;
i++;
}
String user=new String(buf,0,i);
*/
Connection con=DriverManager.getConnection(url,"sa","a9");
PrintSqlException sw=new PrintSqlException(con.getWarnings());
sw.printWarning();
//checkForWarning(con.getWarnings());
DatabaseMetaData dma=con.getMetaData();
System.out.println("Connect to"+dma.getURL());
System.out.println("Driver:"+dma.getDriverName());
System.out.println("Version:"+dma.getDriverVersion());
System.out.println("");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("Select au_id,au_lname,zip,contract from authors ");
while(rs.next())
{
String id=rs.getString(1);
String name=rs.getString("au_lname");
int zip=rs.getInt("zip");
//Boolean contract=rs.getBoolean("contract");
/*获取较大的值,类如图片,影音文件什么的
byte buff=new byte[4096];
InputStream s=rs.getAsciiStream(1);
for(;;)
{
int size=s.read(buff);
if (size==0)
{
break;
}
}
//将读取的数据流写入一个输出流,类如一个文件
output.write(buff,0,size);
* */
System.out.println(id+'|'+name+'|'+zip+' ');//+contract);
}
stmt.close();
//带参数的查询
PreparedStatement pstmt=con.prepareStatement("select * from authors where au_lname>?");
pstmt.setString(1,"d");
ResultSet prs=pstmt.executeQuery();
prs.next();
System.out.println("para:"+prs.getString(2));
pstmt.close();
//查询到某条数据,并将其做修改
PreparedStatement pstmt2=con.prepareStatement("select au_id,au_lname,au_fname from authors where au_lname=?");
pstmt2.setString(1,"white");
ResultSet rst= pstmt2.executeQuery();
if (rst.next())
{
rst.updateString(2,"Stephenewong");
}
pstmt2.executeBatch();
rst=pstmt2.executeQuery();
rst.next();
System.out.println(rst.getString(1)+rst.getString(2)+rst.getString(3));
pstmt2.close();
}
catch(SQLException ex)
{
PrintSqlException pse=new PrintSqlException(ex);
pse.printException();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}