.NET / Oracle: How to execute a script with DDL statements programmatically

后端 未结 3 766
别那么骄傲
别那么骄傲 2020-12-18 01:07

I want to do some programmatical schema manipulation against an oracle database in C#. Therefore, I struggle with some basic issues.

The ddl sql statements are locat

3条回答
  •  被撕碎了的回忆
    2020-12-18 01:56

    Thanks for the semicolon tip!

    My final code to run oracle scripts!

    1) It accepts: - empty lines / comment ( -- ) lines - Multiline DDl / DML commands ending with ;

    2) In case of error it throws an exception with the line number and sql command!

        public async Task ExecuteScript(string _connectionString, string script)
        {
            using (StringReader sr = new StringReader(script))
            {
                var connection = new OracleConnection(_connectionString);
                connection.Open();
    
                string sqlCommand = "";
                string sqlLine; byte lineNum = 0;
    
                while ((sqlLine = sr.ReadLine()) != null)
                {
                    sqlLine = sqlLine.Trim(); ++lineNum;
    
                    if (sqlLine.Length > 0 && !sqlLine.StartsWith("--"))
                    {
                         sqlCommand += (sqlCommand.Length > 0 ? Environment.NewLine : "") + sqlLine;  // Accept multiline SQL
    
                        if (sqlCommand.EndsWith(";"))
                        {
                            sqlCommand = sqlCommand.Substring(0, sqlCommand.Length - 1);
    
                            var command = new OracleCommand(sqlCommand, connection);
    
                            try
                            {
                                await command.ExecuteNonQueryAsync(); 
                            }
                            catch (OracleException ex)
                            {
                                connection.Close();
                                var e2 = new Exception($"{lineNum} - {sqlCommand} 
    {ex.Message}"); throw e2; } } } } connection.Close(); return; } }

提交回复
热议问题