java 操作数据库 sql server (二) jdbc直联操作数据库

package jdbc;
/*
 * jdbc直接操作数据库
 * 
 * */
import java.sql.*;
public class jdbc1 {
	static String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
    static String connectAddr=
    		"jdbc:sqlserver://127.0.0.1:1433;databaseName=Testbase2";
	public static void main(String[] args) {
		//定义需要的对象
		PreparedStatement pst=null;
		Connection ct=null;
		ResultSet rs=null;
		try {
			//初始化对象
			//1,加载驱动
			Class.forName(driverName);
			//2,创建连接
			ct=DriverManager.getConnection(connectAddr,"sa","7");
			pst=ct.prepareStatement("select empno,ename,sal from emp");
			//增删,使用update,查询,使用query
			rs=pst.executeQuery();
			while(rs.next()) {
				//可以适用列名来定位数据,也可以适用列的下标来定位
				System.out.println(rs.getString("ename") + " " + rs.getInt("empno"));
				System.out.println(rs.getInt(1) + " "+ rs.getString(2) + " " + rs.getInt(3));
			}
			
		} 
		catch (Exception e) {
			e.printStackTrace();
		}finally {
			// TODO: handle finally clause
			try {
				if(pst!=null)
				    pst.close();
				if(ct!=null)
				    ct.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}
	}

}

 


package jdbc;
import java.sql.*;
/*
 * java操作ddl语句,创建,删除等操作
 * */
public class jdbc2 {

	static String connectAddr="jdbc:sqlserver://localhost:1433;databaseName=master";
	static String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
    static String order="create database test3";
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Connection ct = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		
		try {
			//加载驱动
			Class.forName(driverName);
			ct=DriverManager.getConnection(connectAddr,"sa","7");
			pst=ct.prepareStatement(order);
			pst.execute();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(ct!=null)
					ct.close();
				if(pst!=null)
					pst.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值