Question Connecting to SQL Server

tAngel

Member
Joined
Jun 24, 2019
Messages
7
Programming Experience
Beginner
hi!! im new here and begginer with C# (english too haha)

i'm trying to learn english because in brazil we do not have (good) forums that help with C# but anyway ...

here is my problem :

i want make one multitool administrative for Grand Chase private server, where you can change, update, delete user and "C, R, U, D" anything in database, i want make one class "Connection.cs" where i can Open and Close my connection whenever i want ...

i get only the first form, the second or third the connection does not open anymore!!


C#:
public class Conexao // Conexao == Connection (br lang)
    {
        public string Data; //Used to get TextBox values with Data, user and Pass to sqlserver
        public string User;
        public string Pass;
        SqlConnection con = new SqlConnection();
        public void receber(string data, string user, string pass) //get textbox values to use here
        {
            this.Data = data; // my variable = textboxes value
            this.User = user;
            this.Pass = pass;
        }
        public Conexao() // Conexao == Connection (br lang)
        {
            con.ConnectionString = (@"Data Source=" + Data + ";Initial Catalog=testeDB;Persist Security Info=True;User ID=" + User + ";Password=" + Pass + ";");
            //con.ConnectionString = (@"Data Source=ANGEL-PC\SQLRGZ;Initial Catalog=testeDB;Persist Security Info=True;User ID=sa;Password=angel123");
        }

        public SqlConnection conectar() //conectar == connecting (br lang)
        {
            if (con.State == System.Data.ConnectionState.Closed)
            {
                con.ConnectionString = (@"Data Source=" + Data + ";Initial Catalog=testeDB;Persist Security Info=True;User ID=" + User + ";Password=" + Pass + ";");
                con.Open();
            }
            else
            {
                con.Close();
            }
            return con;
        }

i would like to know a way to make a connection class that can be accessed by any form to open the connection whenever you need to execute a command in SQL, Thanks!


i really want to learn C# and i will not give up but have someone to make things a little easier sometimes it brings a great happiness, im 4 days trying and today i found this forum,
thank you in advance for helping me.
 
You shouldn't have a separate class to open and close the connection. You should create, open and close the connection wherever you create an execute the command. If you create the command in the form, create the connection there too. ADO.NET is designed such that connection objects should be created, used and discarded. You may well want to have a single connection string stored somewhere and reuse that for every connection but don;t reuse connection objects. Your code to execute a command may look something like this:
C#:
using (var connection = new SqlConnection(GetConnectionString()))
using (var command = new SqlCommand("SELECT * FROM MyTable", connection))
{
    connection.Open();
    
    using (var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            // Use reader here.
        }
    }
}
The data reader and the connection will be closed implicitly, courtesy of the using blocks.
 
Also, I would recommend using a SqlConnectionStringBuilder to build a connection string from parts. What you're doing is not wrong but it is more error-prone.
 
so i have to create this connection method every time i use it right?

I did as follows:

I created a connection method following your example in FORM1:

553



so I decided to test using other forms, I did the following test:

the user type the IP/Sql Instance

554



the txtSql.text receive data perfectly :

555




BUUUUUUT.....
when i try same thing in other form (same project) this happen



i call the function "Connection2" in form2
556




null data values :/

557


but... STILL connecting, why?? Oo...

558
 
You are creating a new instance of Form1. It is not the same instance as the other one that you were previously running.
 
Maybe you would be better first trying to with a static helper to help you get used to understanding the relationships across classes etc. Let me ask you, why do you need a new instance of your form? What happens when you create a new instance of something? And give me some circumstances as an example of when we would need to create a new instance of something?
 
Maybe you would be better first trying to with a static helper to help you get used to understanding the relationships across classes etc. Let me ask you, why do you need a new instance of your form? What happens when you create a new instance of something? And give me some circumstances as an example of when we would need to create a new instance of something?

Sure!

I'll try to explain better...

i would like to create a tool where i can do the following functions:

Add player to database (table users)
559


Add item to invetory.
Change nick name.
Add/Remove Cash in account.
Add/Remove coin.

Ban/Unban Player.

each function in a tab and some of them will be necessary the use of another form
 
I understand what you want to do. But you don't understand the results you are getting, and that is why I am asking you the questions I asked above.

I would love to help you, but in order for me to actually do that, I need you to understand what you're doing. And if you don't understand the answers to the questions in the following quote, there is little point in anyone drip-feeding you an answer, because you still won't know the "why" in the results you are getting. I will reword the quoted questions for you, so they're clearer to understand.

Let me ask you, why do you need a new instance of your form?
What happens when you create a new instance of an object?
And please give me some circumstances as an example of when you think we would need to create a new instance of an object?
If you can answer what I am asking you, you will begin to understand yourself; the result you are getting and most importantly, the why.
 
ooh... alright... sorry ^-^

ok, lets do it..


Let me ask you, why do you need a new instance of your form?
I wanted to get the values of the first form instantiated it in the second form but I realized that the values does not come.


What happens when you create a new instance of an object?
one new memory object created ? im sorry...i've been working on it for over 24 hours and i was not thinking straight ...


And please give me some circumstances as an example of when you think we would need to create a new instance of an object?
my idea was to take the values making a new instance but now after sleeping enough I can think better that it does not make sense
 
I realized that the values does not come.
Why?

one new memory object created
Don't google your answers! It's also not a great way to learn. I've spent most of my life reading MSDN, and will continue to. The understanding of how things works is best learned from those who wrote the documentation for it. Read up on creating instances of objects and forms. Take this starting point Create multiple instances of a form

- Note for example, when you get to the stage of working with SQL connections on a grander scale, you will learn that sometimes (depending on how the connection is declared) a declared SQL connection in a separate form/class that is non-static will need to be instantiated when trying to access from another class/form. If you open the connection state on that classes SQL connection object from within that same class where you declared it first, and If you then create an instance of that class, and its SQL connection object, you are no longer using the same connection with the new instance you just created and are now using, nor can you access the open connection from within the new instance because it is not the same instance. Does that make sense?
my idea was to take the values making a new instance but now after sleeping enough I can think better that it does not make sense
Why does it not make sense? What conclusion did you reach? This is the question you neglected to answer correctly.
when you think we would need to create a new instance of an object?
This article is Ok, It could be better explained but you should research this topic title Static vs. Non-Static method in C# | theburningmonk.com
 
Last edited:
Don't google your answers! It's also not a great way to learn. I've spent most of my life reading MSDN, and will continue to. The understanding of how things works is best learned from those who wrote the documentation for it. Read up on creating instances of objects and forms. Take this starting point Create multiple instances of a form

- Note for example, when you get to the stage of working with SQL connections on a grander scale, you will learn that sometimes (depending on how the connection is declared) a declared SQL connection in a separate form/class that is non-static will need to be instantiated when trying to access from another class/form. If you open the connection state on that classes SQL connection object from within that same class where you declared it first, and If you then create an instance of that class, and its SQL connection object, you are no longer using the same connection with the new instance you just created and are now using, nor can you access the open connection from within the new instance because it is not the same instance. Does that make sense?
i actually typed this manually because i am aware of how a new instance works, it was the subject of last week's lesson from C# in the school but for me there are still many questions that i did not understand 100%(instances, polymorphism, heritage example...), it has not yet become something natural for me...
in theory i studied these subjects but in practice i constantly disappoint myself but i'm trying to give my best ? .

not because of being a new memory space of the same object, i could draw the form that i understand but clearly there must be the same explanation in google, it will not seem original but i understand...


Why does it not make sense? What conclusion did you reach? This is the question you neglected to answer correctly.
Sorry to delay ... i was thinking of some way to solve my problem and after the good "slap" that you gave me (thanks for that) and read some things i came to this conclusion:

i create a new static class to receive my textboxs :

560



and in my form1 i set this values:

561



apparently it works but i have no experience to tell if it is the best way to do it, what do you say?

i look forward to the answer, in this topic i learned much more than i expected, you gave me hope!, you're incredible, thanks sir!
 
As for the original post where the connection successfully opened even though there server name/address was empty, there is this interesting tidbit from the SqlConnection.ConnectionString documentation:
To connect to a local computer, specify "(local)" for the server. If a server name is not specified, a connection will be attempted to the default instance on the local computer.
Notice that in the first connection attempt, the OP was using the address 127.0.0.1 which is the local computer. So that means that he is running the SQL server locally. So later, when the name or address is not supplied, then the code operated exactly as documented: it tried to connect locally.
 
As for the original post where the connection successfully opened even though there server name/address was empty, there is this interesting tidbit from the SqlConnection.ConnectionString documentation:

Notice that in the first connection attempt, the OP was using the address 127.0.0.1 which is the local computer. So that means that he is running the SQL server locally. So later, when the name or address is not supplied, then the code operated exactly as documented: it tried to connect locally.

oh Geez, thanks for the info!

less a doubt in my head, this was making me quite confused, thanks <3.
 
Back
Top Bottom