Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have created a simple Username and Password login form in visual studio using c# which works great I then coded it so that whatever Username and Password was entered into the two textboxes was saved as a string... Now I want to pass those strings as parameters and store them into an SQL query... Any idea how I would go about doing this?
I would highly recommend NOT to store passwords as plain text. Instead look into hashed password methods.
Firstly you will need to specify a connection string. This can be done in the config file as:
<connectionStrings>
<add name="myConnectionString" connectionString="server=ServerAddress;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Now you want to read the connection string from your config file and you can do that in your C# code as:
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
I'm assuming you'll be inserting records. If you are going to update records, then you will need to change the query. For inserting records:
string myQuery = "INSERT INTO MyTable (UserNameColumn,PasswordColumn) VALUES (#UserName, #Password)";
Finally to execute the query and pass our parameters we can do
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(myQuery, connection))
{
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar).Value = UserNameTextBox.Text;
cmd.Parameters.Add("#Password", SqlDbType.NVarChar).Value = PasswordTextBox.Text;
connection.Open();
cmd.ExecuteNonQuery();
}
}
Dont forget to include the namespace using System.Configuration;
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I started programming recently and at the moment I am developing a program with SQL Server 2019 and Visual Studio 2019 in C# that performs simple functions for inserting, deleting and displaying data but I cannot understand how to set up the initial connection with SQL Server. I already connected the Database from Tools->Connect to Database... and the connection test was successful, but now I don't know how to set the connection via SQL Server Authentication by code.
It all depends how you want create the connection really..
At the very top of your form be sure to include
using System.Data.SqlClient;
using System.Configuration;
Depending on how you want to create the connection on whatever button trigger or page load... this scenario would be for you to get specific fields of a query:
string qString = "SELECT value1,value2,value3 FROM database WHERE value 1 = 'hello world'";
using(SqlConnection connection0 = new SqlConnection(ConfigurationManager.ConnectionStrings["CONNECTION_STRING_NAME_HERE"].ToString()))
using(SqlCommand command0 = connection0.CreateCommand())
{
command0.CommandText = qString;
connection0.Open();
using (SqlDataReader reader = command0.ExecuteReader())
{
while (reader.Read())
{
value1string = reader["value1"].ToString();
value2string = reader["value2"].ToString();
value3string = reader["value3"].ToString();
}
}
connection0.Close();
}
Be sure to add the connection string to the app.config file:
<connectionStrings>
<add name="CONNECTION_STRING_NAME_HERE"
connectionString="Data Source=SERVERINSTANCENAME;Initial Catalog=YOUR_DATABASE_NAME;User ID=DATABASE_USERNAME;Password=DATABASE_USER_PASSWORD;" />
</connectionStrings>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am seeking help in storing and saving data in Azure SQL Database. Could anyone please help me with how I can code in C# or the libraries required to do the same
Update:
You can also use the following code, it's a simple .NET framework console project and all the needed assembly is added by default:
using System;
using System.Data.SqlClient;
namespace ConsoleApp13
{
class Program
{
static void Main(string[] args)
{
//define the connection string of azure database.
var cnString = "Server=tcp:xxx.database.windows.net,1433;Initial Catalog=xxx;Persist Security Info=False;User ID=xxx;Password=xxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
//define the insert sql command, here I insert data into the student table in azure db.
string cmdText = #"insert into student
(name,age)
values(#name, #age)";
using (SqlConnection con = new SqlConnection(cnString))
using (SqlCommand cmd = new SqlCommand(cmdText, con))
{
con.Open();
cmd.Parameters.AddWithValue("#name", "yang1");
cmd.Parameters.AddWithValue("#age", 20);
cmd.ExecuteNonQuery();
con.Close();
}
Console.WriteLine("completed***");
Console.ReadLine();
}
}
}
It can insert data successfully into azure database at my side. The screenshot as below:
The official doc provides all the CURD operations. Follow this doc to fetch azure sql database connection string, and set firewall.
The needed assembly is System.Data.dll, which should be added by default when create a project in visual studio.
The sample code is here. For save data, you can see this method static string Build_3_Tsql_Inserts() in this section Methods that return T-SQL statements.
I would request you to start with the Documentation and try the course Provision an Azure SQL database to store application data
Try working threw these.
A Example
Another Example
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Here is my problem. I need to have the user choose a server so I can have the program connect to that server (SQL NOTE This IS In C#)
This is what I have done, but I get an Exception
//first I make a variable that equals to a textbox text
//take the variable and I place it where I would put your sever name
//heres my code
string SQLC = (textBox1.Text);
con.ConnectionString = (#"Data Source=FORDS-PC;
Integrated Security=True;
Connect Timeout=15;
Encrypt=False;
TrustServerCertificate=False;
ApplicationIntent=ReadWrite;
MultiSubnetFailover=False");
here is the ERROR
An unhandled exception of type System.InvalidOperationException
occurred in System.Data.dll)
let me know if you need anything else that i need to tell you
You need to add the database to you connection string.
SQL Server connection string:
connectionString="Data Source=ServerName; Initial Catalog=DatabaseName;
User ID=UserName;Password=Password
Your code
string SQLC = textBox1.Text;
con.ConnectionString = ("Data Source=FORDS-PC;Initial Catalog="+SQLC+";Integrated Security=True;Connect
Timeout=15;Encrypt=False;TrustServerCertificate=False;
ApplicationIntent=ReadWrite;MultiSubnetFailover=False");`
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Additional information: Could not find server 'SS2008' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers.
this is my connection string
"data source=123-pc;initial catalog=Inquire_Commerce;user id=sa;password=sasasa;multipleactiveresultsets=True;application name=EntityFramework"
here is my code
var cmd = conn.CreateCommand();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "dbo.AdvancedProductSearch";
cmd.CommandTimeout = 90;
cmd.Connection.Open();
AddParameter(cmd, "searchtext", queryParameters.Keyword);
AddParameter(cmd, "pagesize", queryParameters.PageSize);
AddParameter(cmd, "pageno", queryParameters.PageNo);
AddParameter(cmd, "attributevalues", queryParameters.AttNamValue);
AddParameter(cmd, "word1", word1);
AddParameter(cmd, "word2", word2);
AddParameter(cmd, "word3", word3);
AddParameter(cmd, "word4", word4);
AddParameter(cmd, "word5", word5);
var reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
and i got this error in this line
var reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
This is most likely not a coding problem but a problem in SQL Linked Servers Configuration. Look at the content of the stored procedure that you're calling. There will be a statement (SELECT, INSERT, UPDATE, DELETE etc.), that refers to a row source on a linked server that is named SS2008. Make sure that on the SQL Server you're connecting to, a linked server by that name exists, and is accessible.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
What is wrong with my code or connection string? Always can't connect to database.
string c = null;
SqlConnection sql;
c = "Data Source=127.0.0.1, 3306;Network Library=DBMSSOCN;Initial Catalog=testowa;User ID=kuba;Password=123";
sql = new SqlConnection(c);
try
{
sql.Open();
MessageBox.Show("Connected!");
sql.Close();
}
catch (Exception ex)
{
MessageBox.Show("not connected :(");
}
You are trying to connect to a MySql database not to a Sql Server one. These are two different products and require different connection strings, different classes and different ADO.NET Providers.
First, download and install the MySql Connector/NET from here
Second, go to your project references and add a reference to
MySql.Data.dll
Third, remove the using System.Data.SqlClient and add using MySql.Data.MySqlClient in every source file where you have the database code
Fourth, change your code to use the appropriate classes like
MySqlConnection, MySqlCommand, MySqlDataReader, etc...
Finally, use a proper connection string for MySql
using(MySqlConnection sql = #"Data Source=127.0.0.1;
Database==testowa;uid=kuba;Pwd=123;Port=3306"))
{
try
{
sql.Open();
MessageBox.Show("Connected!");
}
catch (Exception ex)
{
MessageBox.Show("not connected :(" + ex.Message);
}
}