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 17 days ago.
Improve this question
protected void btnSave_Click(object sender, EventArgs e)
{
string sql = #"UPDATE Users
SET Initials = #Ini
WHERE Common_Name = #cn";
using (var con = new SqlConnection("***"))
{
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
cmd.Parameters.AddWithValue("#cn", ddlUser.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Ini", txtInitials.Text);
cmd.ExecuteNonQuery();
con.Close();
}
}
Not really quite sure what is going on, I am unable to get this to update the database.
The only way I was able to get this work was not using parameters and hard coding it which is not what I'm looking to do.
I can provide more code upon request, wasn't quite sure if it is necessary.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I've been working with ASP NET Web Forms for a while and we have been communicating with the database like this
using (MySqlConnection con = new MySqlConnection(conexao))
{
try
{
string sql = string.Format("SELECT ID_Cliente, Nome, Cnpj, FL_Filial FROM cadastro_cliente WHERE ID_Cliente = {0}", ID_Cliente);
MySqlCommand cmd = new MySqlCommand(sql, con);
MySqlDataReader reader = null;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
flf = Convert.ToInt32(reader["FL_Filial"].ToString());
}
}
catch (MySqlException ex)
{
string vLog = "#Erro#: " + ex.Message;
EscreveLog(vLog);
}
finally
{
con.Close();
con.Dispose();
}
}
My question is, is it right if I use the same way to communicate with the database? Like not using Models or anything. Reminding that I'm new to ASP NET Razor Pages.
You could program anything, Visual Studio allows you to do anything in Controllers. But.. see comments of Franz ! they are relevant. To avoid the pitfalls Franz has pointed out, I would recommend using Entity Framework instead of directly using SQL. That would introduce models (DBContext) anyway.
ASP.NET was designed for MVVM and the only difference with ASP.NET Core is the implementation. I would say the answer to this question is yes, skipping the model is wrong.. unless you do not want to adhere to MVVM programming methods.
https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel
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
I try to backup my database but I get an error:
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
The backup or restore was aborted.
This is my code, and my database is up to 20GB in size.
string query = "Backup database Testing to disk='C:\Test.bak'"
con.Open();
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
How can I change a timeout value in C# or query?
Use CommandTimeout property (Documentation), 0 means no limit.
Add
cmd.CommandTimeout = 0
to your code:
string query = "Backup database Testing to disk='C:\Test.bak'"
con.Open();
cmd = new SqlCommand(query, con);
cmd.CommandTimeout = 0;
cmd.ExecuteNonQuery();
con.Close();
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 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;