Okay, so I'm getting a weird error with this function.
It's saying:
Exception Details: System.Data.Odbc.OdbcException: ERROR [HY000] [MySQL][ODBC 5.1 Driver][mysqld-5.0.27-community-nt]Column 'CommentNumber' cannot be null
But I can verify that the variable commentnumber is indeed getting a value. If I put a Response.Write right before the
command.Parameters.Add("#CommentNumber", commentnumber);"
line I get 1 returned (which is correct).
public string commenter(string commentnumber, string postnumber, string commentname, string commentemail, string comment) {
OdbcConnection connection = new OdbcConnection();
connection.ConnectionString = "server=<address>;"
+ "database=<database>;"
+ "uid=<username>;"
+ "password=<password>;"
+ "DRIVER={MySQL ODBC 5.1 Driver}";
string CommandText = "INSERT INTO Comments (CommentNumber, PostNumber, Name, Email, PostTime, Comment) VALUES (#CommentNumber, #PostNumber, #Name, #Email, #PostTime, #Comment)";
connection.Open();
try {
OdbcCommand command = new OdbcCommand(CommandText, connection);
command.Parameters.Add("#CommentNumber", commentnumber);
command.Parameters.Add("#PostNumber", postnumber);
command.Parameters.Add("#Name", commentname);
command.Parameters.Add("#Email", commentemail);
command.Parameters.Add("#PostTime", DateTime.Now);
command.Parameters.Add("#Comment", comment);
command.ExecuteNonQuery();
command.Dispose();
command = null;
}
catch(Exception ex) {
// Response.Write("There's been a problem. Please contact technical support.");
throw new Exception(ex.ToString(), ex);
Response.End();
}
finally {
connection.Close();
}
return "Success!";
}
ODBC uses ? for placholders. Since you're using #CommandNumber in the raw sql string, it's actually being interpreted by MySQL as an undefined server-side variable, hence the "cannot be null" error.
The second parameter is the OdbcType, not the value. Try using .AddWithValue()
What type is the field CommentNumber?.
Specifies the type of the parameter to add command.Parameters
Related
Trying to insert a new record into an MS Access .accdb file. When I run the code below, it appears to work fine. No errors are presented, but nothing updates in the database file either. I have verified that the database is in an accessible location.
selectedNote is an object with the three listed parameters. The only field I'm not including in the query string is the ID field which is autonumber.
string scon = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source = |DataDirectory|AMS.accdb";
string str = "INSERT INTO Notes ([ItemID], [Note], [Note Date]) VALUES (?, ?, ?)";
try
{
using (OleDbConnection con = new OleDbConnection(scon))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("ItemID", selectedNote.ItemID);
cmd.Parameters.AddWithValue("Note", selectedNote.Note);
cmd.Parameters.AddWithValue("Note Date", selectedNote.NoteDate.ToString("dd-MM-yy"));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
Thanks all, hopefully I can get this hammered out.
EDIT: Curiously, I just found that if I hard-code a path to the .accdb file with a line like the following, it actually does write to that file. So I guess the question becomes why is it not working on the build path where the database is in the same path as the exe.
AppDomain.CurrentDomain.SetData("DataDirectory","C:\temp");
I have tried setting DataDirectory to something like AppDomain.CurrentDomain.BaseDirectory, but this doesn't seem to work either.
A date should not be inserted as text, and you do have the DateTime value, thus:
cmd.Parameters.AddWithValue("Note Date", selectedNote.NoteDate);
I can not find what is the error in this code. According to me it's good and hope to execute properly but I am getting an error:
ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.7.11]
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ViewBatchByID' at line 1
My code Is
string Message = null;
OdbcCommand Cmd = new OdbcCommand();
Cmd.Connection = Connection.con;
Cmd.CommandText = "ViewBatchByID";
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.AddWithValue("#p0", 1);
try
{
Cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
Message = ex.Message.ToString();
}
HERE ViewBatchByID is my stored procedure and it's working fine from server.
Check the connection settings for the server. Is the Database set?
Driver={SQL Server};Server=(local);Trusted_Connection=Yes;Database=AdventureWorks;
I get syntax error when using 'Insert into' SQL command using c#. I'm using Access db to store some data.
Surprisingly, when I copy the exact command into MS Access to try if it's not correct, it works like charm. I'm a bit confused! I appreciate any idea or help in this regard. Here is my code:
using (OleDbConnection connection = new OleDbConnection(Global.ConString))
{
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO Users(Name,UserName,Password,Customers,Jobs,Invoice,Statement,Reports,Users) values (#name,#UserName,#Password,#Customers,#Jobs,#Invoice,#Statement,#Reports,#Users)";
command.Parameters.AddWithValue("#name",fullName.Text );
command.Parameters.AddWithValue("#UserName", userName.Text);
command.Parameters.AddWithValue("#Password", passWord.Text);
command.Parameters.AddWithValue("#Customers", Customers.Checked);
command.Parameters.AddWithValue("#Jobs", Jobs.Checked);
command.Parameters.AddWithValue("#Invoice", Invoice.Checked);
command.Parameters.AddWithValue("#Statement", Statement.Checked);
command.Parameters.AddWithValue("#Reports", Report.Checked);
command.Parameters.AddWithValue("#Users", userDef.Checked);
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
if (recordsAffected > 0)
{
foreach (Control item in newRecord.Controls)
{
if (item is TextBox) item.ResetText();
}
timer1.Enabled = true;
}
else
MessageBox.Show("Insert Fail");
}
catch (OleDbException err)
{
MessageBox.Show("Somthing wrong. Error no. is: " + err.ErrorCode + "..." + err.Message);
}
}
}
Most likely your issue is the use of a reserved word as an identifier, specifically 'Password'. Wrap that column name in brackets, i.e. [Password] and you should be good to go.
It's best to avoid reserved words if possible. Generally speaking, you should not be storing unhashed passwords in your database so a column name like 'PasswordHash` is appropriate and avoids this issue.
I am trying to execute a command with OdbcCommand in c# but it seems i can't even open the connection. This is the data I got to create the Connection String
Server: APPRDNETEZZA (192.168.0.64)
Web Server: beamprdwb3
ODBC DSN Name (64bit): NZ_FUTUREBRANDS
User: MSTR_ADMIN
Port: 5480
This is my code
string connetionString = null;
OdbcConnection cnn;
OdbcCommand cmd;
string sql = null;
connetionString = "Driver={NetezzaSQL}; servername=APPRDNETEZZA ;
database=NZ_FUTUREBRANDS; port=5480; username=MSTR_ADMIN;
password=mstr17Uz1%4;";
sql = "CREATE EXTERNAL TABLE X_STORE_GROUP_GUID_12345(" +
"STORE_ID VARCHAR(10)," +
"STORE_NAME VARCHAR(50)," +
"USERID Varchar(255)," +
"import_guid Varchar(255), )" +
"USING(" +"DATAOBJECT('/apnas01/vol2.nfs.Data/ap_prod/data/store_upload/scripts/12345_guid_12345')" + "logDir '/apps/ap_prod/log'" + " delimiter ','" + " "; ";
cnn = new OdbcConnection(connetionString);
try
{
cnn.Open();
Console.WriteLine("Connection Opened ");
cmd = new OdbcCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
result = "Executed sucessfully";
}
catch (Exception ex)
{
result = "Error" + ex.InnerException.ToString();
}
The error happens when it tries to open the connection. While debugging it gave me this inner exception
[ODBC Driver Manager] Data source name not found and no default driver
specified
I have the Odbc driver installed in my machine. I dont know it this is happening cuz the connection string is in bad format. I have spent many hours trying to figure it out why doesnt work. Appreciate any kind of help. Thanks
Here is an example Netezza ODBC connection string:
https://www.connectionstrings.com/netezzasql-odbc-driver/
Driver={NetezzaSQL};servername=myServerAddress;port=myPortNumber;
database=myDataBase;username=myUsername;password=myPassword;
Your connection string basically looks the same:
connetionString = "Driver={NetezzaSQL}; servername=APPRDNETEZZA ;
database=NZ_FUTUREBRANDS; port=5480; username=MSTR_ADMIN;
password=xyz;";
SUGGESTIONS:
Make the entire connection string (everything inside the quotes) ONE LINE. Don't break the string into separate lines.
Or use "+" (like you did with your SQL string).
Copy the driver (nsqlodbc.dll?) into the same directory as your .exe assembly (path issue?)
Try both the 32-bit and 64-bit drivers (CPU platform issue?)
Definitely post back what you find!
I have a problem with inserting a TextBox value into a SqlServer table. I wrote that code, but when I run the form it raises a runtime error: "a network-related or instance-specific error occurred while establishing a connection to sql server". Thanks in advance.
public partial class Add_Client : Form
{
SqlConnection clientConnection;
string connString;
SqlCommand insertCommand;
public Add_Client()
{
InitializeComponent();
connString = "Data Source=.//INSTANCE2;Initial Catalog=Clients;Integrated Security=True";
clientConnection = new SqlConnection();
clientConnection.ConnectionString = connString;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlCommand insertCommand = new SqlCommand();
insertCommand.Connection = clientConnection;
insertCommand.CommandText = "INSERT INTO Client_Info values(#Client_Name,#AutorizationNo,#IssueType,#Status)";
insertCommand.Parameters.Add("#Client_Name",SqlDbType.NVarChar,60).Value=txt_Name.Text;
insertCommand.Parameters.Add("#AutorizationNo", SqlDbType.Int, 60).Value =txt_Auth.Text.ToString();
insertCommand.Parameters.Add("#Issue", SqlDbType.Text, 200).Value =txt_Iss.Text;
insertCommand.Parameters.Add("#Status", SqlDbType.TexT, 15).Value=txt_sta.TexT;
insertCommand.Connection.Open();
insertCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (clientConnection != null)
{
clientConnection.Close();
}
}
}
}
the .// in the host name in your connection string shouldn't be there. i wouldn't expect it to work. you should just have the machine name itself there.
You need to check your connecting string, u may find it usefull:
http://www.connectionstrings.com/
If you are sure about the connection string then please check your database status.
The parameter names in SQL should not contain blanks. I you want to use blanks you have to enclose the parameter name in square brackets.
Is your connection string correct? That basically means it couldn't connect to the server.
Also, just a tip - I wouldn't do this:
insertCommand.Parameters.Add("#Autorization No", SqlDbType.Int, 60).Value =txt_Auth.Text.ToString();
...
Its just asking for trouble. Instead copy it, sanitize it and make sure that it won't cause an exception.