java访问SQLServer2008数据库方式一:jdbc-odbc桥连接

import java.sql.*;

public class Test2
{
	public static void main(String[] args) {

		//定义需要的对象
		Connection ct = null;
		ResultSet rs = null;
		PreparedStatement ps = null;

		try
		{
			//加载驱动
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			
			//得到连接
			ct = DriverManager.getConnection("jdbc:odbc:mytest");
			
			//创建ps
//			ps = ct.prepareStatement("select * from dept where deptNo=? and loc=?");
//			
//			ps.setInt(1, 11);
//			ps.setString(2, "北京");
//			
//			rs = ps.executeQuery();
//			
//			while(rs.next())
//			{
//				System.out.println(rs.getInt(1) + "\t" + rs.getString(2)
//						+ "\t" + rs.getString(3));
//			}
			//添加一条记录
			ps = ct.prepareStatement("insert into dept values(?,?,?)");
			ps.setInt(1, 20);
			ps.setString(2, "部长");
			ps.setString(3, "后勤部");
			
			int res = ps.executeUpdate();
			
			if(1 == res)
			{
				System.out.println("ok");
			}
			else
			{
				System.out.println("error");
			}
			
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally{
			try
			{
				if(rs != null)
				{
					rs.close();
				}
				if(ct != null)
				{
					ct.close();
				}
				if(ps != null)
				{
					ps.close();
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}
}

你可能感兴趣的:(java,数据库)