Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I want to create a REST WebService which is connected to a MySQL database. But I got stuck at a point and don´t really know how to get further.
This is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SimpleRESTServer.Models;
using MySql.Data;
namespace SimpleRESTServer
{
public class PersonPersistance
{
private MySql.Data.MySqlClient.MySqlConnection conn;
public PersonPersistance()
{
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=Local Instance MySQL80; pwd=;database=employeedb";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
}
}
public long savePerson(Person personToSave)
{
String sqlString = " INSERT INTO tblpersonnel (FirstName, LastName) VALUES ('"+ personToSave.FirstName + "','" + personToSave.LastName + "')";}
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sqlString, conn);
cmd.ExecuteNonQuery();
long id = cmd.LastInsertedId;
return id;
}
}
So my problem is that in the savePerson function something doesn´t work. When I write 'sqlString' and 'conn' ind the MySqlCommand part, it always get underlined red. I don´t really know what´s wrong.
I listend to this guys tutorial: https://youtu.be/LpySuvYPMZQ
I hope somebody can help me.
Thanks for your help in advance!
You are closing the method at the sqlString variable. Just after the semi colon you have a closing curly braces.
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 5 years ago.
Improve this question
how to save video in database sql server using xamarin android web service and display in listview
I would strongly advise not to store videos in your database due to the following reasons:
1). Doing so would bloat your database size
2). Slow down the performance of the database
3). It opens your application to Denial of Service attacks (DDOS).
You should look forward to storing your videos on a file dedicated storage like:
1). Cloud Storage.
2). FTP storage.
3). Server's file system.
4). Etc...
If you really want to store videos on your database for testing or bench marking purposes, you can try the following code:
using System;
using System.Data;
using System.Data.SqlClient;
namespace Portal.WebApp.Models
{
public class DbBlobSaver
{
#region Public Methods
public void Execute(byte[] fileBytes)
{
using (var dbConnection = new SqlConnection("Data Source = .; Initial Catalog = BlobsDatabase; Integrated Security = SSPI"))
{
var command = BuildCommand(dbConnection);
var blobParameter = BuildParameter(fileBytes);
command.Parameters.Add(blobParameter);
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
// Log errors here
}
finally
{
command.Connection.Close();
}
}
}
#endregion
#region Private Methods
private SqlParameter BuildParameter(byte[] fileBytes)
{
var blobParameter = new SqlParameter("#BlobFile", SqlDbType.Binary);
blobParameter.Value = fileBytes;
return blobParameter;
}
private SqlCommand BuildCommand(SqlConnection connection)
{
var command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO BlobsTable(BlobFile)" + "VALUES (#BlobFile)";
return command;
}
#endregion
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
hello i have a problem with getting exception of "ExecuteNonQuery requires an open and available Connection. The connection's current state is closed."
public void AddCustomer(Customer customer)
{
string connectionString = #"Data Source=LIRON-PC\SQLEXPRESS;Initial Catalog=C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\MatokMmagnet.mdf;Integrated Security=True";
using (m_sqlConnection = new SqlConnection(connectionString))
{
m_cmd = new SqlCommand();
m_cmd.CommandType = CommandType.Text;
m_cmd.Connection = m_sqlConnection;
m_cmd.Parameters.AddWithValue("#id", customer.id);
m_cmd.Parameters.AddWithValue("#FirstName", customer.FirstName);
m_cmd.Parameters.AddWithValue("#LastName", customer.LastName);
m_cmd.Parameters.AddWithValue("#Password", customer.Password);
m_cmd.CommandText = "INSERT INTO Customers (id, FirstName, LastName, Password)VALUES (#id, #FirstName, #LastName, #Password)";
try
{
m_cmd.ExecuteNonQuery();
}
catch(Exception e)
{
Console.WriteLine( e.Message);
}
finally
{
m_sqlConnection.Close();
}
}
}
Like the error says you must open the connection before executing the query like this :
public void AddCustomer(Customer customer)
{
string connectionString = #"Data Source=LIRON-PC\SQLEXPRESS;Initial Catalog=C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\MatokMmagnet.mdf;Integrated Security=True";
using (m_sqlConnection = new SqlConnection(connectionString))
{`
m_sqlConnection.open();
//....
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
My code for parameterized data insertion is not working. I get the error:
'System.Data.SqlClient.SqlCommand' does not contain a definition for 'Parameter' and no extension method 'Parameter' accepting a first argument of type 'System.Data.SqlClient.SqlCommand' could be found (are you missing a using directive or an assembly reference?)
I added using System.Data.SqlClient.SqlCommand but it made no difference. Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class add_data_ch1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\qwhizz_ch1_Database.mdf;Integrated Security=True;User Instance=True");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
}
protected void btn_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand(#"insert into data_Table values (#fname, #lname, con);
cmd.Parameter.AddWithValue("#fname", fnameTextBox.Text);
cmd.Parameter.AddWithValue("#lname", lnameTextBox.Text);
cmd.ExecuteNonQuery();
con.Close();
}
}
Would appreciate if someone can show me where the code error is or what is missing. Thanks in advance.
Should be Parameters
cmd.Parameters.AddWithValue("#fname", fnameTextBox.Text);
//Add rest of Parameters here
SqlCommand cmd = new SqlCommand(#"insert into data_Table values (#fname, #lname, con);
I believe you're just missing an end parenthesis and quotation marks.
SqlCommand cmd = new SqlCommand(#"insert into data_Table values (#fname, #lname)", con);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a very simple Windows Form. I want to add data to a database by using it.
In my C# winforms solution, I created a data source named db_studentDataSet and connected my database db_student. Whenever I run my solution, I get the following exception:
SqlException was unhandled: Login failed for user 'sa'
Here's my code:
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SimpleEnrollmentSystem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonAdd_Click(object sender, EventArgs e)
{
this.Validate();
this.studentsBindingSource.EndEdit();
studentsTableAdapter.Insert("Ahmed", "Rownak", "Male", 13, "Malibagh");
}
}
}
Here's a image of my form:
Here's my database:
CREATE TABLE Students
(
StudentID int primary key,
FirstName string,
LastName string,
Gender string,
Age int,
Address string
)
Note that I've only coded for the Add button functionality.
What is wrong with my code? Or is it anything else? Maybe the way I'm trying to achieve this is wrong? Is there a better way, in that case?
I'm using Visual Studio 2012 Ultimate and SQL Server 2012 Express Edition.
EDIT - 1: I have changed my buttonAdd_Click() method.
private void buttonAdd_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection("Data Source=SAADMAAN;Initial Catalog=db_student;User ID=sa;Password=***********");
con1.Open();
SqlCommand cmd1 = new SqlCommand("INSERT INTO Students(StudentID, FirstName, LastName, Gender, Age, Address) VALUES('" + studentIDTextBox.Text + "','" + firstNameTextBox.Text + "','" + lastNameTextBox.Text + "','" + genderTextBox.Text + "','" + ageTextBox.Text + "','" + addressTextBox.Text +"')",con1);
cmd1.ExecuteNonQuery();
con1.Close();
}
According to user Kiran Hegde's suggestion, I changed the password into clear text in my connection string.
SqlConnection con1 = new SqlConnection("Data Source=SAADMAAN;Initial Catalog=db_student;User ID=sa;Password=open");
That solved the problem. So silly of me, I skipped this obvious thing.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am developing a C# Windows application. I have used access database. When I selecting data from database I am getting data, but when inserting data it's not gets inserted and also it's not showing any error.
But when I run the same insert query in Access it gets inserted. Here is my code:
public void connCheck()
{
try
{
cn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database\MyDatabase.mdb;Persist Security Info=True;Jet OLEDB:Database Password=2013");
if (cn.State == ConnectionState.Closed)
cn.Open();
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
}
public bool ExecuteNonQuery()
{
try
{
connCheck();
string sqlQuery = "INSERT INTO tblResult(ExamSet,SetId,FullMarks,ObtainedMarks,MarksPercentage,ElapsedTime,LastQIndex,CreatedDate,Completed)
Values(1,27,'200.00',0,0,0,1,DATE(),'N')";
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
cmd.CommandText = sqlQuery;
cmd.ExecuteNonQuery();
return true;
}
catch(OleDbException ex)
{
ErrorMsg = ex.ToString();
return false;
}
finally
{
cn.Close();
cn.Dispose();
cmd.Dispose();
}
}
You did not defined your cmd..
add this line
OledbCommand cmd=new OledbCommand();
How about replacing your query code like this
string sqlQuery = "INSERT INTO tblResult([ExamSet],[SetId],[FullMarks],[ObtainedMarks],[MarksPercentage],[ElapsedTime],[LastQIndex],[CreatedDate],[Completed])
Values(1,27,'200.00',0,0,0,1,DATE(),'N')";
Update:
One of the issues could be Security warning that disables the content.
Try and see if this works (Go to your MDB):
Click on 'External Data' tab
There should be a Security Warning that states "Certain content in the database has been disabled"
Click the 'Options' button
Select 'Enable this content' and click the OK button
Try parameterised queries via cmd.Parameters.Add or AddRange. Example
var cmd = new SqlCommand("INSERT INTO tbl_name (a, b, c) VALUES (#a, #b, #c)");
cmd.Parameters.AddRange(new[] { new SqlParameter("#a", field1), new SqlParameter("#b", field2), new SqlParameter("#c", field2) });
(Posted on behalf of the OP).
Thanks everyone for your help, I got the solution. Actually there is no problem in my code. Problem is that I have created database file in a folder. But when I build the project it created a duplicate database with same folder an file name in bin folder.
So every time it gets inserted in that database. And I was checking in the database file which I have created. So I thought it's not working.