jdbc测试数据库连接

Mysql数据库测试程序:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/*
 * 测试mysql连接
 */

public class MysqlTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		try {
			Class.forName("org.gjt.mm.mysql.Driver");
			conn = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/login", "root", "root"); //login为数据库名称,
			conn.setAutoCommit(false); // 当设为false时就要显示的进行提交,conn.commit(),否则数据库不会有任何改变

			stmt = conn.createStatement();
				String sql = "select * from usertable ";
			ResultSet rs = stmt.executeQuery(sql);
			
ResultSetMetaData metaData = rs.getMetaData(); //得到记录集的列名
			
			for(int i=0;i<metaData.getColumnCount();i++){
				System.out.print(metaData.getColumnName(i+1)+"\t");
			}
			System.out.println();

			while (rs.next()) {
				System.out.print(rs.getInt("id")+"\t");
				System.out.print(rs.getString("name")+"\t");
				System.out.println(rs.getString("password")+"\t");
			}
			String sql2 = "insert into user values('z','女','')";
			stmt.executeUpdate(sql2);
			conn.commit();
			rs.close();
			stmt.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}


SQL Server测试程序

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


public class SqlServerTest {
	public SqlServerTest() {
	}

	public static void main(String args[]) {
		try {
			try {
				Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
			} catch (ClassNotFoundException e) {

				e.printStackTrace();
			}
			Connection conn

			= DriverManager
					.getConnection("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=login","sa","sa"); 
			Statement stmt = conn.createStatement();
			String sql = "select   *   from     employee ";
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				System.out.println("TestName: " + rs.getString("name"));
			}
			rs.close();
			stmt.close();
			conn.close();
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
	}

}

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