JDBC连接模型

package TestConnection;

import java.sql.Connection;
import java.sql.DriverManager;

public class TestSQLServer {
	
	public Connection getConnection() {

		Connection conn = null;
		//SQL Server 的默认端口是1433
		String url = "jdbc:microsoft:SQLServer://localhost:1433;DatabaseName=DB_JXC";
		try {
			Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
			conn = DriverManager.getConnection(url, "sa","123");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return conn;
	}
	public static void main(String[] args) {

		TestSQLServer test = new TestSQLServer();
		Connection conn = test.getConnection();
		if(conn == null) {
			System.out.println("连接上不了");
		}else {
			System.out.println("连接上了!!");
		}

	}

}

 

 

 

测试 :

package TestConnection;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestJXC {

	Connection conn;
	Statement stmt;
	ResultSet rs ;
	
	TestSQLServer tss = new TestSQLServer();
	
	//查询操作
	public void list() {
		
		Connection conn = tss.getConnection();
		try {
			Statement stmt = conn.createStatement();
			String sql = "select * from [tb_username]";
			ResultSet rs =stmt.executeQuery(sql);
			
			while(rs.next()) {
				String username =  rs.getString("username");
				System.out.println(username);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	//添加操作
	
	public void add() {}
	
	//删除操作
	public void delete() {}
	
	//更新修改操作
	public void update() {}
	
	public static void main(String[] args) {
		TestJXC tjsx = new TestJXC();
		tjsx.list();
	}
}

 

你可能感兴趣的:(java,sql,SQL Server,jdbc,Microsoft)