⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 simpletest.java

📁 一些数据库的java开发编程
💻 JAVA
字号:
package jdbcbook.ch04;

import java.sql.*;


// JDBC访问数据库的简单例子
public class SimpleTest
{ 
	// 定义驱动程序的名称
	public static final String drivername = "com.microsoft.jdbc.sqlserver.SQLServerDriver";

	// 定义数据库的URL
	public static final String url = "jdbc:microsoft:sqlserver://192.168.0.100:1433;DatabaseName=pubs;";
	// 定义访问数据库的用户名
	public static final String user = "sa";
	// 定义访问数据库的密码
	public static final String password = "12345";

	public static void main( String[] args )
	{
		//设定查询SQL语句
		String queryString = "SELECT title, price FROM TITLES";

		Connection conn = null; 
		Statement st = null; 
		ResultSet rs = null; 
		try 
		{ 
			// 1. 加载驱动程序
			Class.forName( drivername );

			// 2. 建立连接
			conn = DriverManager.getConnection( url, user, password );

			// 3. 创建Statement
			st = conn.createStatement();

			// 4. 执行SQL语句,获得查询结果
			rs = st.executeQuery( queryString );

			// 5. 输出查询结果
			while( rs.next() )
			{
				System.out.println( "书名:" + rs.getString( "title" ) 
					+ "(定价:" + rs.getDouble( "price" ) + ")" );
			}

			// 6. 关闭资源
			rs.close();
			st.close();
			conn.close();

		} 
		catch (Throwable t) 
		{ 
			// 错误处理:输出错误信息
			t.printStackTrace( System.out );
		} 
		finally 
		{ 
			// finally子句总是会被执行(即使是在发生错误的时候)
			// 这样可以保证ResultSet,Statment和Connection总是被关闭
			try 
			{ 
				if (rs != null) 
					rs.close(); 
			} 
			catch(Exception e) {} 

			try 
			{ 
				if (st != null) 
					st.close(); 
			} 
			catch(Exception e) {} 

			try 
			{ 
				if (conn != null) 
					conn.close(); 
			} 
			catch (Exception e){} 
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -