0317

使用列索引作为参数性能更好,使用列名作为参数可读性更好。
以下区别在于一个把连接数据库语句写在程序里,另一个是通过配置文件mysql.ini来保存数据库连接信息。
import java.sql.*;
public class ConnMySql
{
	public static void main(String[] args) throws Exception
	{
		Class.forName("com.mysql.jdbc.Driver");     //加载数据库驱动。
		try ( //Java7,自动关闭资源。
			//使用DriverManager获取数据库连接, 其中返回的Connection就代表了Java程序和数据库的连接
			Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/select_test", "root" , "1234");
			Statement stmt = conn.createStatement();  //通过Collection对象创建Statement对象。
			//executeQuery():只能执行查询语句,执行后返回代表查询结果的ResultSet对象。
			//多表连接查询
			ResultSet rs = stmt.executeQuery("select s.* , teacher_name"+ " from student_table s , teacher_table t"+ " where t.teacher_id = s.java_teacher")
			 )
		{
			// ResultSet有系列的getXxx(列索引 | 列名),用于获取记录指针指向行、特定列的值,不断地使用next()将记录指针下移一行,
			//如果移动之后记录指针依然指向有效行,则next()方法返回true。
			while(rs.next())
			{
				System.out.println(rs.getInt(1) + "\t"+ rs.getString(2) + "\t"+ rs.getString(3) + "\t"+ rs.getString(4));
			}
		}
	}
}



import java.util.*;
import java.io.*;
import java.sql.*;
public class ExecuteDDL
{
	private String driver;
	private String url;
	private String user;
	private String pass;
	public void initParam(String paramFile) throws Exception
	{
		// 使用Properties类来加载属性文件
		Properties props = new Properties();
		props.load(new FileInputStream(paramFile));
		driver = props.getProperty("driver");
		url = props.getProperty("url");
		user = props.getProperty("user");
		pass = props.getProperty("pass");
	}
	public void createTable(String sql) throws Exception
	{
		Class.forName(driver);   // 加载驱动
		try(
		Connection conn = DriverManager.getConnection(url , user , pass);  // 获取数据库连接
		Statement stmt = conn.createStatement())  // 使用Connection来创建一个Statment对象
		{
			stmt.executeUpdate(sql); // 可执行DML或者DDL语句。
		}
	}
	public static void main(String[] args) throws Exception
	{
		ExecuteDDL ed = new ExecuteDDL();
		ed.initParam("mysql.ini");
		ed.createTable("create table jdbc_test "+ "( jdbc_id int auto_increment primary key, "+ "jdbc_name varchar(255), "+ "jdbc_desc text);");
		System.out.println("-----Mission Completed-----");
	}
}


猜你喜欢

转载自huadianfanxing.iteye.com/blog/2363842
017
今日推荐