eclipseは、単純な単一テーブルから単一テーブルへのデータベース移行を実現

3180 ワード

MySQLデータベースsqlserverデータベースへのテーブルの移行
要件:データベースとテーブルを事前に作成する
package mysql;

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

public class Move {

	private String url1 = "jdbc:mysql://localhost/servlet";
	private String url2 = "jdbc:sqlserver://localhost:1433;databasename=test";
	private Connection con;
	private Statement st;
	private ResultSet rs;
	private ResultSetMetaData rsmd;
	int column;

	
	//    
	public Connection getConnection1()
	{
		try {
			//    
			Class.forName("org.gjt.mm.mysql.Driver");
			//    
			return DriverManager.getConnection(url1,"root","123");
			//sqlst = sqlconn.createStatement();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	//    
	public Connection getConnection2() 
	{
		try {
			//    
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			//    
			return DriverManager.getConnection(url2,"sa","123");
			//myst = sqlconn.createStatement();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	// mysql    
	public void extract()
	{
		String sql ="select * from student"; 
		con = getConnection1();
		System.out.println("   1    ");
		try {
			
			st = con.createStatement();
			System.out.println("  sql       !");
			rs = st.executeQuery(sql);
			System.out.println("  sql    ");
			rsmd = rs.getMetaData();
			column = rsmd.getColumnCount();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	// sqlserver    
	public void insert()
	{
		String sql;
		con = getConnection2();
		System.out.println("   2    ");
		try {
			st = con.createStatement();
			System.out.println("  sql       !");
			while(rs.next())
			{
				sql = "insert into student values ("+rs.getInt(1)+",'"+rs.getString(2)+"',"+rs.getInt(3)+",'"+rs.getString(4)+"','"+rs.getString(5)+"')";
				st.executeUpdate(sql);
			}
			System.out.println("  sql    ");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//    
	public void release()
	{
		if(rs!=null)
		{
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(st!=null)
		{
			try {
				st.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(con!=null)
		{
			try {
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("      !");
	}
	
	public static void main(String[] arg) {
		Move move = new Move();
		move.extract();
		move.insert();
		move.release();
	}
}

参考文献:
https://www.cnblogs.com/oukele/p/9626006.html
https://blog.csdn.net/angle_wing_wh/article/details/78685172