JDBC for MSSql2005 简单示例

package com.anllin.sqlserver;

import java.sql.*;

public class SqlserverTest
{
public static void main(String[] args)
{
sqlsserver2005Test();
}

public static void sqlsserver2005Test()
{
String connectionUrl
= "jdbc:sqlserver://localhost:1433;databaseName=test;username=sa;password=123";

Connection conn
= null;
Statement stmt
= null;
ResultSet rs
= null;

try
{
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn
= DriverManager.getConnection(connectionUrl);
conn.setAutoCommit(
false);
stmt
= conn.createStatement();
rs
= stmt.executeQuery("select * from T_User");

while (rs.next())
{
System.out.print(rs.getInt(
"id") + " ");
System.out.print(rs.getString(
"name") + " ");
System.out.println(rs.getDate(
"birthday"));
}

conn.commit();
}
catch (Exception e)
{
if(null != conn)
{
try
{
conn.rollback();
}
catch (Exception e2)
{
e2.printStackTrace();
}
}
}
finally
{
if(null != rs)
{
try
{
rs.close();
rs
=null;
}
catch (Exception e2)
{
e2.printStackTrace();
}
}
if(null != stmt)
{
try
{
stmt.close();
stmt
= null;
}
catch (Exception e2)
{
e2.printStackTrace();
}
}
if(null != conn)
{
try
{
conn.close();
conn
=null;
}
catch (Exception e2)
{
e2.printStackTrace();
}
}
}
}
}

  

posted @ 2011-08-09 13:41  水之原  阅读(617)  评论(0编辑  收藏  举报