I write this C# Code for insert one text data to my database table:
SQLiteConnection con = new SQLiteConnection("Data Source=tDB1.sqlite;Version=3;");
string q1 = "INSERT INTO tMembers(mName) VALUES(?)";
SQLiteCommand cmd1 = new SQLiteCommand(q1, con);
cmd1.Parameters.AddWithValue("#mName", txtName.Text);
con.Open();
cmd1.ExecuteNonQuery();
con.Close();
I copy my tDB1.sqlite to my program folder and Create tMembers table in sqlite.
when i run my program, program debugger show ""cmd1.ExecuteNonQuery();"" line and display to me: SQLite error no such table
can any help me?
thank you.
It is a little to weak look for a file based just on current directory. If you are sure the database is placed exactly in the same dir of the executable ( that is when debugging from visual studio $projectdir$\bin\debug you can enforce the path as in the following code:
SQLiteConnection con = new SQLiteConnection(string.Format("Data Source={0};Version=3;"
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),"tdb1.sqlite"))
);
Change the command string
string q1 = "INSERT INTO tMembers(mName) VALUES(?)";
to
string q1 = "INSERT INTO tMembers(#mName) VALUES(?)";
There is no need to keep corresponding to the column's name, but it must be the same with the args' name when executing the whole command. More info about this, you could search "PL/SQL" in google.
Besides, did you execute this command with "VALUES(?)"? I'm not sure that could work or not, you could execute INSERT INTO tMembers(#mName) DEFAULT VALUES instead, if there is no NOT NULL constraint.
Related
I am trying to update my database with the window form I have created, however an error occurred when I execute the code:
An unhandled exception of type 'System.InvalidOperationException'
occurred in System.Data.dll" at comm.ExecuteNonQuery();
Here is the code that I used to connect to my database. Was the code I used to update the database wrong?
string conn=ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
SqlCommand comm = new SqlCommand("UPDATE ExerciseInstruction SET Accumulated_Daily_Sets_Completed = '0' WHERE ExerciseInstructionsID ='" + exerciseInstructionID +"'", connection);
comm.ExecuteNonQuery();
Here is the complete error message :
ExecuteNonQuery requires an open and available Connection. The
connection's current state is closed.
The error message explain all. The command cannot be executed if the code doesn't know how to reach the database. Just a call to connection.Open should fix the problem, however I think you need to use a proper way to execute the query.
This is called Parameterized query. In this way you don't concatenate strings together to form you query text but use parameters to pass values to the database engine and a special formatted string containing the parameters placeholders.
There are two main advantages to do so. It is not possible to target your code with Sql Injection hacks and you don't have to handle quoting around your strings (an infinite source of bugs)
string conn=ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
string cmdText = #"UPDATE ExerciseInstruction
SET Accumulated_Daily_Sets_Completed = 0
WHERE ExerciseInstructionsID =#exid";
using(SqlConnection connection = new SqlConnection(conn))
using(SqlCommand comm = new SqlCommand(cmdText, connection))
{
connection.Open(); // Need this before executing the query
comm.Parameters.Add("#exid", SqlDbType.Int).Value = exerciseInstructionID;
comm.ExecuteNonQuery();
}
Hi have this simple ASPX site setup. In the code behind, I'm connecting to an Oracle database, throwing a SELECT query and putting the result to a DataSet that I can then use/display on the website.
The problem: The query should give me result (works fine inside SQLDeveloper), but when I'm filling the DataSet, it gives me 0 rows every time. No Oracle errors show up, connection to the database opens up fine and the query looks correct.
I would have liked to get some kind of an Oracle error, that would have been easier to troubleshoot. I have tried to find a solution online, but haven't found anything that has helped with my problem.
Here is the relevant code I'm using:
using System.Data.OracleClient;
private OracleConnection conn = new OracleConnection();
-- // Below everyting is in the same method
var ds = new DataSet();
-- // conn.ConnectionString is corretly set
conn.Open(); // connection to database is opened
OracleCommand command = conn.CreateCommand();
var sql = "SELECT * FROM someTable"; -- // the SQL query
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
OracleDataAdapter adapter = new OracleDataAdapter(command);
ds.Tables.Clear();
adapter.Fill(ds);
Here the DataSet (ds) should be full, but it's always empty. Any pointers would be most welcome. Please let me know if I'm missing some information.
I have trouble converting this to stored procedure
//The string included in the sql statement:
string employer = Session["Employer"].ToString();
then the sql statement
update tblWorkData set EmployerName='"+txtemployername.text+"' where EmployerName='"+Employer+"' //the string above
This works fine in asp.net
But when I turn it into stored procedure,
create proc updateWork
#EmployerName nvarchar(max)
as
begin
update tblWorkData set EmployerName=#EmployerName where EmployerName=#EmployerName
end
Now when I execute the sp on asp.net,
string update = "updateWork '"+employer+"','"+txtemployername.text+"'";
I got an error saying "too many arguements". What should I do?
Your stored procedure only takes one argument and you're calling it with two. To fix this you need to alter the procedure to take two arguments like this:
create proc updateWork
#EmployerName nvarchar(max),
#Employer nvarchar(max)
as
begin
update tblWorkData set EmployerName=#EmployerName where EmployerName=#Employer
end
I changed the whereclause as I guess you meant it to be. As it was before it didn't actually do anything at all.
On a side note you might want to look into how to properly call procedures and how to add parameters in a way that isn't vulnerable to SQL injection.
You have to connect to the database in order to execute sql statements:
string employer = Session["Employer"].ToString();
// assume connectionString is a valid connection string
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = "updatework";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#EmployerName", employer);
command.ExecuteNonQuery();
}
Right now I am able to execute a script from my website in an HTTPpost method.
string scriptDirectory = "c:\\Users\\user\\Documents";
string sqlConnectionString = "Integrated Security=SSPI;" +
"Persist Security Info=True;Data Source=ARES";
DirectoryInfo di = new DirectoryInfo(scriptDirectory);
FileInfo[] rgFiles = di.GetFiles("*.sql");
foreach (FileInfo fi in rgFiles)
{
FileInfo fileInfo = new FileInfo(fi.FullName);
string script = fileInfo.OpenText().ReadToEnd();
SqlConnection connection = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(connection));
server.ConnectionContext.ExecuteNonQuery(script);
connection.Close();
}
Atm the script is creating a new database (database is not dynamic yet). I want to pass in parameters that a user of the website enters and then pass that into the sql script. Basically I want them to choose the name of the database that is to be created.
The SQL command's are right at the beginning of the script.
CREATE DATABASE [This is where the name will be passed to]
GO
USE[This is where the name will be passed to]
Edit:
I have this code
SqlCommand createDbCommand = new SqlCommand();
createDbCommand.CommandText = "CREATE DATABASE [#DataBase]";
createDbCommand.Parameters.Add("#DataBase", SqlDbType.Text);
createDbCommand.Parameters["#DataBase"].Value = client.HostName;
Must I manually enter this into the top of my script now?
Create a new SqlCommand and set the script CommandText to your script's text and then set parameters using cmd.Parameters.Add.
Using parameters with CRUD operations is simple enough (google for "t-sql parameters" for thousands of resources), however parameterising type names is more involved, for that there's a lengthy MSDN article here: http://msdn.microsoft.com/en-us/library/bb510489.aspx
If you're looking for something quick 'n' dirty, you could roll your own parameterisation system by putting replacement sequences in your sql files and using a regular expression to make each replacement, such as using the syntax "{{fieldName}}".
What I am missing to get data from temporary table. This is showing error like Invalid object name #emp. Please help me
I am using Asp.net.
Dim sqlcmd = New SqlCommand("select * into #emp from employees", conn)
sqlcmd.ExecuteNonQuery()
sqlcmd = New SqlCommand("select * from #emp", conn)
Dim dr As SqlDataReader = sqlcmd.ExecuteReader
See Above query is working fine and data is going into temporary table. but it is not selecting again through second one query.
Thanks
Try to use Global Temporary table instead of Local Temporary tabel like.. ##emp
or
You can just use a stored procedure which has all the SQL statement you want to execute and return your desired recordset.