Detailed explanation of the method of converting sql server to oracle in asp.net tutorial

巴扎黑
Release: 2017-09-01 15:05:00
Original
1755 people have browsed it

This article mainly introduces to you the relevant information about converting sql server into oracle in asp.net development. The article introduces the steps of implementation in detail through sample codes and pictures. It is very useful for everyone's study or work. It has certain reference and learning value. Friends who need it can come and study together.

Preface

Because some time ago our company project was to convert sql server to oracle, and found that there was less information about this online, so here it is Share your experience and record the problems. Not much to say below, let’s take a look at the detailed introduction:

At first I studied for a while and then downloaded

oracle 11g version and PL /SQL (client) The difference from sql server is that Oracle does not have its own client and needs to use third-party software to run PL/SQL. It is a sqldeveloper. I think PL/SQL is more stable. But if both are installed, they will complement each other.

oracle is prone to errors such as no monitoring, please refer to

http://www.jb51.net/article/91184.htm

Then use

to create table spaces and users, which can be found online

Now that everything is installed, let’s start converting sql server to oracle

First of all, I tried many ways to convert the database, but they were all more or less problematic because they were two different databases. In the end, I decided to write a program myself. Convert

code and post it

Link string


<add key="OracleConnectionString" value="Password=123;User ID=SA;Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost )(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=ORCL)))"/>
 
 <add key="SqlServerConnectionString" value="server=localhost;database=Table;uid=sa;pwd=123"/>
Copy after login


##

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TransplantSQL
{
 public partial class Form1 : Form
 {
 public static string OracleConnectionString = System.Configuration.ConfigurationSettings.AppSettings["OracleConnectionString"];
 public static string SqlServerConnectionString = System.Configuration.ConfigurationSettings.AppSettings["SqlServerConnectionString"];
 public Form1()
 {
  InitializeComponent();
 }

 private void button2_Click(object sender, EventArgs e)
 {
  OracleConnection con = new OracleConnection(OracleConnectionString);
  try
  {
  con.Open();
  if (con.State == System.Data.ConnectionState.Open)
  {
   label5.Text = "连接成功";
  }
  }
  catch (OracleException se)
  {
  label5.Text = "连接失败";
  }

  finally
  {
  con.Close();
  }
 }

 private void button3_Click(object sender, EventArgs e)
 {
  SqlConnection con = new SqlConnection(SqlServerConnectionString);
  try
  {
  con.Open();
  if (con.State == System.Data.ConnectionState.Open)
  {
   label4.Text = "连接成功";
  }
  }
  catch (SqlException se)
  {
  label4.Text = "连接失败";
  }

  finally
  {
  con.Close();
  }
 }

 private void button1_Click(object sender, EventArgs e)
 {
  if (textBox1.Text == "")
  {
  DataTable tablenames = GetTableNames();
  foreach (DataRow item in tablenames.Rows)
  {
   string tablename = item["Name"].ToString().ToUpper();
   setdata(tablename);
  }
  }
  else
  {
  setdata(textBox1.Text);
  }

  label2.Text = "成功";
 }

 private static void setdata(string tablename)
 {
  // 查找有没有此表 如果没有就加
  int et = Convert.ToInt32(GetSingle("select count(*) from user_tables where table_name = &#39;" + tablename + "&#39;"));
  if (et <= 0)
  {
  DataTable tableInfo = GetTableInfo(tablename);
  string addtablesql = "CREATE TABLE {0}({1})";
  string cs = string.Empty;
  string biaoshi = string.Empty;
  foreach (DataRow citem in tableInfo.Rows)
  {
   cs += citem["字段名"].ToString();
   if (citem["类型"].ToString() == "int" || citem["类型"].ToString() == "bit" || citem["类型"].ToString() == "decimal")
   {
   cs += " NUMBER(" + (Convert.ToInt32(citem["长度"]) > 38 ? 38 : Convert.ToInt32(citem["长度"])) + (Convert.ToInt32(citem["小数位数"])>0?(","+Convert.ToInt32(citem["小数位数"])):"") + ")";
   }
   else if (citem["类型"].ToString() == "nvarchar" || citem["类型"].ToString() == "float")
   {
   cs += " VARCHAR2(" + (Convert.ToInt32(citem["长度"]) == -1 ? 4000 : Convert.ToInt32(citem["长度"]) * 2) + ")";
   }
   else if (citem["类型"].ToString() == "datetime")
   {
   cs += " DATE";
   }
   
   cs += citem["主键"].ToString() == "1" ? " primary key " : "";
   if (citem["标识"].ToString() == "1")
   {
   biaoshi = citem["字段名"].ToString();
   }
   cs += citem["默认值"].ToString() != "" ? " default " + citem["默认值"].ToString() + " " : "";
   cs += citem["允许空"].ToString() == "1" ? "," : " NOT NULL,";
  }
  cs = cs.Substring(0, cs.Length - 1);
  string tempsql = string.Format(addtablesql, tablename, cs);
  GetSingle(tempsql);
  if (biaoshi != string.Empty)
  {
   #region 判断是否有序列号 没有就创建 就是自动标识
   int xuliehao = 0;
   try
   {
   xuliehao = Convert.ToInt32(GetSingle(string.Format(@"select Seq_{0}.nextval from sys.dual", tablename)));
   }
   catch { }
   if (xuliehao <= 0)
   {
   #region 为了让序列不重复 取最大值为min 值
   int max = Convert.ToInt32(GetSingle(string.Format("select max({1}) from {0}", tablename, biaoshi),null));
   #endregion
   string sequence = string.Format(@"create sequence Seq_{0} start with {1} increment by 1 nomaxvalue minvalue 1 nocycle nocache", tablename, (max+1));//创建标识
   GetSingle(sequence);
   }
   #endregion
   #region 创建序列的触发器
   string chufaqisql = string.Format(@"CREATE OR REPLACE TRIGGER T_{0} 
      BEFORE INSERT ON {0} FOR EACH ROW WHEN (new.{1} is null)
      begin
      select Seq_{0}.nextval into:new.{1} from dual;
      end;", tablename, biaoshi);//创建触发器
   GetSingle(chufaqisql);
   #endregion
   #region 创建唯一约束
   //string weiyisql = string.Format(@"create unique index U_{0} on {0} ({1})", tablename, biaoshi);
   //GetSingle(weiyisql);
   #endregion
  }
  //int count = Convert.ToInt32(GetSingle("SELECT count(1) FROM " + tablename));
  //if (count < 10000)
  //{
  DataSet ds = Query("SELECT * FROM " + tablename);
  DataTable dt = ds.Tables[0];
  string columnsNames = string.Empty;
  string values = string.Empty;
  for (int i = 0; i < dt.Columns.Count; i++)
  {
   columnsNames += dt.Columns[i].ColumnName + ",";

  }
  columnsNames = columnsNames.Substring(0, columnsNames.Length - 1);
  foreach (DataRow dr in dt.Rows)
  {
   values = string.Empty;
   for (int i = 0; i < dt.Columns.Count; i++)
   {
   if (dr[i] != DBNull.Value)
   {
    if (dr[i].ToString() != "")
    {
    if (dt.Columns[i].DataType == Type.GetType("System.Double")
     || dt.Columns[i].DataType == Type.GetType("System.Decimal")
     || dt.Columns[i].DataType == Type.GetType("System.Int32"))
    {
     values += dr[i] + ",";
    }
    else if (dt.Columns[i].DataType == Type.GetType("System.String"))
    {
     values += "&#39;" + dr[i].ToString().Replace(&#39;\&#39;&#39;, &#39;‘&#39;) + "&#39;,";
    }
    else if (dt.Columns[i].DataType == Type.GetType("System.DateTime"))
    {
     values += "to_date(&#39;" + dr[i] + "&#39;,&#39;YYYY/MM/DD HH24:MI:SS&#39;),";
    }
    else if (dt.Columns[i].DataType == Type.GetType("System.Boolean"))
    {
     if (dr[i].ToString() == "False")
     {
     values += "0,";
     }
     else { values += "1,"; }
    }
    }
    else
    {
    values += "chr(32),";
    }
   }
   else
   {
    values += "NULL,";
   }
   }
   values = values.Substring(0, values.Length - 1);
   string osql = "Insert into " + tablename + "(" + columnsNames + ") values(" + values + ")";
   GetSingle(osql);
  }
  //}
  }
 }

 private static DataTable GetTableNames()
 {
  string sql = string.Format(@"SELECT Name FROM SysObjects Where XType=&#39;U&#39; ORDER BY Name");
  DataSet ds = Query(sql);
  return ds.Tables[0];
 }
 private static DataTable GetTableInfo(string tableName)
 {
  string sql = string.Format(@"SELECT (case when a.colorder=1 then d.name else null end) 表名, 
  a.colorder 字段序号,a.name 字段名,
  (case when COLUMNPROPERTY( a.id,a.name,&#39;IsIdentity&#39;)=1 then &#39;1&#39;else &#39;&#39; end) 标识, 
  (case when (SELECT count(*) FROM sysobjects 
  WHERE (name in (SELECT name FROM sysindexes 
  WHERE (id = a.id) AND (indid in 
  (SELECT indid FROM sysindexkeys 
  WHERE (id = a.id) AND (colid in 
  (SELECT colid FROM syscolumns WHERE (id = a.id) AND (name = a.name))))))) 
  AND (xtype = &#39;PK&#39;))>0 then &#39;1&#39; else &#39;&#39; end) 主键,b.name 类型,a.length 占用字节数, 
  COLUMNPROPERTY(a.id,a.name,&#39;PRECISION&#39;) as 长度, 
  isnull(COLUMNPROPERTY(a.id,a.name,&#39;Scale&#39;),0) as 小数位数,(case when a.isnullable=1 then &#39;1&#39;else &#39;&#39; end) 允许空, 
  REPLACE(REPLACE(isnull(e.text,&#39;&#39;),&#39;(&#39;,&#39;&#39;),&#39;)&#39;,&#39;&#39;) 默认值,isnull(g.[value], &#39; &#39;) AS [说明]
  FROM syscolumns a 
  left join systypes b on a.xtype=b.xusertype 
  inner join sysobjects d on a.id=d.id and d.xtype=&#39;U&#39; and d.name<>&#39;dtproperties&#39; 
  left join syscomments e on a.cdefault=e.id 
  left join sys.extended_properties g on a.id=g.major_id AND a.colid=g.minor_id
  left join sys.extended_properties f on d.id=f.class and f.minor_id=0
  where b.name is not null
  And d.name=&#39;{0}&#39; 
  order by a.id,a.colorder", tableName);
  DataSet ds = Query(sql);
  return ds.Tables[0];
 }

 public static DataSet Query(string SQLString)
 {
  using (SqlConnection connection = new SqlConnection(SqlServerConnectionString))
  {
  DataSet ds = new DataSet();
  try
  {
   connection.Open();
   SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
   command.Fill(ds, "ds");
  }
  catch (System.Data.SqlClient.SqlException ex)
  {
   throw new Exception(ex.Message);
  }
  return ds;
  }
 }

 public static object GetSingle(string SQLString)
 {
  using (OracleConnection connection = new OracleConnection(OracleConnectionString))
  {
  using (OracleCommand cmd = new OracleCommand())
  {
   try
   {
   PrepareCommand(cmd, connection, null, SQLString, null);
   object obj = cmd.ExecuteScalar();
   cmd.Parameters.Clear();
   if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
   {
    return null;
   }
   else
   {
    return obj;
   }
   }
   catch (OracleException e)
   {
   throw e;
   }
  }
  }
 }

 private static void PrepareCommand(OracleCommand cmd, OracleConnection conn, OracleTransaction trans, string cmdText, OracleParameter[] cmdParms)
 {
  if (conn.State != ConnectionState.Open)
  conn.Open();
  cmd.Connection = conn;
  cmd.CommandText = cmdText;
  if (trans != null)
  cmd.Transaction = trans;
  cmd.CommandType = CommandType.Text;//cmdType;
  if (cmdParms != null)
  {


  foreach (OracleParameter parameter in cmdParms)
  {
   if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
   (parameter.Value == null))
   {
   parameter.Value = DBNull.Value;
   }
   cmd.Parameters.Add(parameter);
  }
  }
 }

 public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
 {
  using (SqlConnection connection = new SqlConnection(SqlServerConnectionString))
  {
  using (SqlCommand cmd = new SqlCommand())
  {
   try
   {
   PrepareCommand(cmd, connection, null, SQLString, cmdParms);
   object obj = cmd.ExecuteScalar();
   cmd.Parameters.Clear();
   if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
   {
    return null;
   }
   else
   {
    return obj;
   }
   }
   catch (System.Data.SqlClient.SqlException e)
   {
   throw e;
   }
  }
  }
 }

 private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
 {
  if (conn.State != ConnectionState.Open)
  conn.Open();
  cmd.Connection = conn;
  cmd.CommandText = cmdText;
  if (trans != null)
  cmd.Transaction = trans;
  cmd.CommandType = CommandType.Text;//cmdType;
  if (cmdParms != null)
  {


  foreach (SqlParameter parameter in cmdParms)
  {
   if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
   (parameter.Value == null))
   {
   parameter.Value = DBNull.Value;
   }
   cmd.Parameters.Add(parameter);
  }
  }
 }
 }
}
Copy after login

This code is suitable for my database conversion. If you need it, you can modify it.

Oracle does not have auto-increment, but a sequence. The other sequence can be triggered by a trigger. This is troublesome. Overall, it’s pretty good

Then I changed my original program string link to the oracle link and posted it above

First

System.Data.SqlClient; Change the reference to System.Data.OracleClient;

Then just change it when you see the error report. Just change it from Sql to Oracle

Then I will post it There are some differences between sqlserver and oracle that do not report errors

Query the first number of data


select * from (SELECT * FROM Table) where rownum<100
Copy after login

Convert other formats into string format

select to_char (other formats, string format) such as

select to_char(sysdate,'yyyy-mm-dd') from dual

##String interception

(Intercepted string, starting position, length)

select substr(&#39;111222&#39;,3,2) from dual
Copy after login

Convert string format to time format

select to_date(&#39;2017-08-03&#39;,&#39;yyyy-mm-dd&#39;) from dual
Copy after login

sql parameterized placeholder, @ cannot be used. Use:

SELECT * FROM Table where ID=:ID
Copy after login

System time

getdate()

Changed to sysdateGet the current automatic growth column ID

select Seq_Table.currval from dual
Copy after login

Seq_Table is the name of the automatic growth column , each table is different, so you need to find the name corresponding to the auto-increase column set by the current

table

After changing everything, wait until the program does not report an error and run it

There are some problems with 32 and 64 bits. Various opinions on the Internet say that the project properties should be changed to X86 The project caused a lot of problems

So I studied it for a long time and finally came up with several results

First of all, if it is a console or form program Just check the preferred 32-bit option in the project

If it is an asp.net page program, it is not so simple

My machine is 64-bit Then I installed Oracle and the client are both 64-bit. Logically speaking, I shouldn’t get any 64-bit errors.

Then the Internet said that I need to install a 32-bit Instant Client Setup

Then I downloaded Just install the program and it will be fine.

But I tried the same method again on the server and it didn’t work. I searched a lot of information and finally reinstalled iis (actually I had to re-register the framework).

It is best to install the 32-bit version the same as the oracle version

At that time, I downloaded many versions for debugging and sometimes when installing Instant Client Setup It will get stuck at one point. You can try it a few more times and if it still doesn’t work, find another one!

You can find it in the control panel after installation

Also post the backup and restore command, open it with CMD and run it to modify the corresponding parameters

Exp sa/123@ORCL file=C:\OracleBack\back_%date:~0,4%%date:~5,2%%date:~8,2%.dmp owner=sa

IMP sa/123 BUFFER=64000 FILE=C:\OracleBack\back_20170821.dmp FROMUSER=SA TOUSER=SA
Copy after login

The above is the detailed content of Detailed explanation of the method of converting sql server to oracle in asp.net tutorial. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!