eclipse实现简单的、单表到单表的数据库迁移

 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

你可能感兴趣的:(eclipse实现简单的、单表到单表的数据库迁移)