SQL problem

MiPakTeh 1,286 Reputation points
2022-06-04T07:53:21.037+00:00

Hi All,
I Create the Database name TRIAL and run , it is OK then delete it and write the code then run again.
Error message;
System.Data.SqlClient.SqlException
HResult=0x80131904
Message=A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Source=.Net SqlClient Data Provider
StackTrace:
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at Store_3.Form1.button1_Click(Object sender, EventArgs e) in C:\Users\family\source\repos\Store_3\Store_3\Form1.cs:line 28
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Store_3.Program.Main() in C:\Users\family\source\repos\Store_3\Store_3\Program.cs:line 19

Inner Exception 1:
Win32Exception: The network path was not found

here is code;

using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
using System.Windows.Forms;  
using System.Data.SqlClient;  
  
  
namespace Store_3  
{  
    public partial class Form1 : Form  
    {  
        public Form1()  
        {  
            InitializeComponent();  
  
        }  
  
            private void button1_Click(object sender, EventArgs e)  
        {  
            SqlConnection conn = new SqlConnection("server=(localdb)\v11.0");  
            using (conn)  
            {  
                conn.Open();  
                string sql = string.Format(@"CREATE DATABASE[TRIAL] ON PRIMARY (NAME=TRIAL_A, FILENAME='{0}\TRIAL_A.mdf)')  
                                          LOG ON(NAME=TRIAL_log, FILENAME='{0}\TRIAL_A.ldf')", @"C:\Users\family\Documents\");  
                SqlCommand command = new SqlCommand(sql, conn);  
                command.ExecuteNonQuery();  
            }  
              
        }  
  
        private void button2_Click(object sender, EventArgs e)  
        {  
  
        }  
  
        private void button3_Click(object sender, EventArgs e)  
        {  
  
        }  
    }  
}  

Error at: conn.Open()

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
6,960 questions
No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 29,236 Reputation points Microsoft MVP
    2022-06-04T13:53:59.477+00:00

    I would break down the code, something like the following. I didn't do anything to the create other than changed how the path is done.

    https://github.com/karenpayneoregon/closet-code/tree/master/CreateLocalDb

    class DataOperations
    {
        /// <summary>
        /// Change to match your path for the database
        /// </summary>
        public static string DataPath = @"C:\OED";
        public static string ConnectionString()
        {
            return @$"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TRIAL;Integrated Security=True";
        }
        public static string MasterConnectionString()
        {
            return @$"Server=(localdb)\MSSQLLocalDB";
        }
        public static void Create()
        {
    
            using var cn = new SqlConnection(MasterConnectionString());
            using var cmd = new SqlCommand() { Connection = cn };
    
            cmd.CommandText = @$"CREATE DATABASE[TRIAL] ON PRIMARY (NAME=TRIAL_A, FILENAME='{DataPath}\TRIAL_A.mdf)')
                                           LOG ON(NAME=TRIAL_log, FILENAME='{DataPath}\TRIAL_A.ldf')";
    
            try
            {
    
                cn.Open();
                cmd.ExecuteNonQuery();
    
                Console.WriteLine("Created");
    
            }
            catch (Exception localException)
            {
                Console.WriteLine(localException);
            }
        }
    
        /// <summary>
        /// Open connection
        /// </summary>
        public static void Open()
        {
    
            using var cn = new SqlConnection(ConnectionString());
    
            cn.Open();
            Console.WriteLine("Open");
    
        }
    
        /// <summary>
        /// Create tables and optionally populate
        /// </summary>
        public static void CreateTables()
        {
            throw new NotImplementedException();
        }
    
        /// <summary>
        /// Run select statements
        /// </summary>
        public static void ReadData()
        {
            throw new NotImplementedException();
        }
    }
    
    No comments

1 additional answer

Sort by: Most helpful
  1. Ken Tucker 5,801 Reputation points
    2022-06-04T13:39:25.777+00:00

    You might need to change your connection string to this

          Server=(localdb)\v11.0;Integrated Security=true;
    
    No comments