环境变量批处理,红色部分是需要你自己根据实际环境设置
@echo on
set JAVA_HOME=C:\Oracle\Java\jdk
set CLASSPATH=.;%JAVA_HOME%\lib;%JAVA_HOME%\lib\tools.jar
set CLASSPATH=%CLASSPATH%;"E:\Resource\Java\JDBC\sqljdbc_3.0.1301.101_chs\sqljdbc_3.0\chs\sqljdbc4.jar"
set PATH=%JAVA_HOME%\bin;%PATH%
cmd
确认数据库工作正常,准备好JDBC驱动,设置了环境变量后,代码如下。
package sql2005;
import java.sql.*;
public class Main
{
public static void main ( String[] args )
{
// 创建一个SQL2005的连接字符创.
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=CaseOpenInfo;user=caseopeninfo;password=123456";
// 初始化JDBC驱动.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try
{
//设置类.
Class.forName ( "com.microsoft.sqlserver.jdbc.SQLServerDriver" );
con = DriverManager.getConnection ( connectionUrl );
// 设置SQL命令
String SQL = "select * from /"case/"";
// stmt = con.createStatement ();
stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); // 如果存在 last 或者 first 方法则使用
rs = stmt.executeQuery ( SQL );
// 遍历结果
while (rs.next ())
{
System.out.println ( rs.getString ( 1 ) + " " + rs.getString ( 2 ) );
}
}
catch (Exception e)
{
e.printStackTrace ();
}
finally
{
if ( rs != null )
{
try
{
rs.close ();
}
catch (Exception e)
{
}
}
if ( stmt != null )
{
try
{
stmt.close ();
}
catch (Exception e)
{
}
}
if ( con != null )
{
try
{
con.close ();
}
catch (Exception e)
{
}
}
}
}
}
-----------------------------------------------
编译代码
javac sql2005.java
执行代码
java sql2005