I am completely blind with this Error. I'm more of a Java man than an ASP one. So here is my code and my question :
Here is my code that produce the error :
protected void ButtonOk_Click(object sender, EventArgs e)
{
// OracleConnection connect = new OracleConnection();
// connect.ConnectionString = ConfigurationManager.ConnectionStrings["Absensi2.Properties.Settings.Setting"].ConnectionString;
//// SqlConnection connect = new SqlConnection(getConnection());
var sql = "insert into master_dosen('NIP','NAMA_DOSEN','KETERANGAN') values (:NIP, :NAMA_DOSEN, :KETERANGAN)";
using (OracleConnection c = new OracleConnection(ConfigurationManager.ConnectionStrings["Absensi2.Properties.Settings.Setting"].ConnectionString))
{
c.Open();
using (OracleCommand cmd = new OracleCommand(sql, c))
{
cmd.Parameters.Add(":NIP", TextBoxNIP.Text);
cmd.Parameters.Add(":NAMA_DOSEN", TextBoxNamaDosen.Text);
cmd.Parameters.Add(":KETERANGAN", TextBoxKeterangan.Text);
cmd.ExecuteNonQuery();
GridView1.DataBind();
}
c.Close();
}
The error is :
ORA-00928: missing SELECT keyword
in line cmd.ExecuteNonQuery();
I already search and it says deprecated. is it true?
NB : I am using ODP.NET, and I am using visual studio 2010.
The problem with your query is that you are wrapping column names with single quotes which makes them string literal.
To fix the problem, just remove the single quotes around the column names:
var sql = "insert into master_dosen(NIP,NAMA_DOSEN,KETERANGAN) ...";
protected void ButtonOk_Click(object sender, EventArgs e)
{
// OracleConnection connect = new OracleConnection();
// connect.ConnectionString = ConfigurationManager.ConnectionStrings["Absensi2.Properties.Settings.Setting"].ConnectionString;
//// SqlConnection connect = new SqlConnection(getConnection());
var sql = "insert into master_dosen(NIP,NAMA_DOSEN,KETERANGAN) values (:NIP, :NAMA_DOSEN, :KETERANGAN)";
using (OracleConnection c = new OracleConnection(ConfigurationManager.ConnectionStrings["Absensi2.Properties.Settings.Setting"].ConnectionString))
{
c.Open();
using (OracleCommand cmd = new OracleCommand(sql, c))
{
cmd.Parameters.Add(":NIP", TextBoxNIP.Text);
cmd.Parameters.Add(":NAMA_DOSEN", TextBoxNamaDosen.Text);
cmd.Parameters.Add(":KETERANGAN", TextBoxKeterangan.Text);
cmd.ExecuteNonQuery();
GridView1.DataBind();
}
c.Close();
}
Try this it will work ,I think you miss the sql insert syntax
Related
This question already has answers here:
Read data from SqlDataReader
(13 answers)
Closed 2 years ago.
I'm trying to read data from the data source and I got this error in the ExecuteReader method,
When I try to show the result in some label.
I'm getting the error here idlabel.Text = myraeder("id"); under myreader varibale
private void Searchbtn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(dataConnectin);
con.Open();
string searchsql = "SELECT * from Table WHERE Name=" + searchtxt.Text + "";
SqlCommand cmd = new SqlCommand(searchsql, con);
SqlDataReader myraeder;
myraeder = cmd.ExecuteReader();
myraeder.Read();
idlabel.Text = myraeder("id");
}
Use square brackets instead of round brackets.
Convert the field to string.
idlabel.Text = myraeder["id"].ToString();
Read the data in this way:
idlabel.Text = myraeder["id"].ToString();
con.Close();
And do not forget to close the connection after getting required data.
There are so many errors that are obvious. Let me show you a better way to write code. Follow me!
Give the variables proper names and casing.
Use asynchrony.
Use parameters in sql queries.
Release resources by wrapping them in using.
Enclose names in brackets in sql.
private async void SearchButton_Click(object sender, EventArgs e)
{
using (var connection = new SqlConnection(connectionString))
{
await connection.OpenAsync();
string searchSql = "SELECT * from [Table] WHERE [Name]=#name";
using (var command = new SqlCommand(searchSql, connection))
{
command.Parameters.Add("name", SqlDbType.NVarChar).Value = searchTextBox.Text;
using (var reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
idLabel.Text = reader["id"].ToString();
}
}
}
}
}
As title says I've used odbcconnection to sqlconnection and for the life of me cant get it to work.. Copied a bunch of code from this site but cant get them both to work.
The program just hangs so maybe I am doing something wrong, but would appreciate maybe a bare bones template that i could just fill in the connection details and bulk copy the table to table..
using (OdbcConnection myConnection = new OdbcConnection())
{
string myConnectionString = #"Driver={Microsoft Access Driver (*.mdb)};" +
"Dbq=//####/data/Toronto/wrkgrp/wrkgrp30/Business Risk Oversight and Control/DATA INTEGRITY/CDE/CDE Testing Portal Requirements/Migration Requirements/RCM/Mutual Funds/Mutual Funds.mdb;";
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
//execute queries, etc
OdbcCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM RCM_MF_New_Accounts_Samples";
OdbcDataReader reader = cmd.ExecuteReader(); // close conn after complete
DataTable myDataTable = new DataTable();
myDataTable.Load(reader);
//myConnection.Close();
string destinationConnectionString = "Data Source=####;Initial Catalog=DYOF_STAGING_BROC;User ID=;Password=;Connection Timeout=999";
SqlConnection destination = new SqlConnection(destinationConnectionString);
SqlBulkCopy bulkData;
//destination.Open();
Exception ex = null;
try
{
Console.WriteLine("step1");
bulkData = new SqlBulkCopy(destinationConnectionString, SqlBulkCopyOptions.FireTriggers);
bulkData.BulkCopyTimeout = 1;
bulkData.DestinationTableName = "Load_CTR_Sample_Account_Opening2";
bulkData.WriteToServer(myDataTable);
bulkData.Close();
Console.WriteLine("moved from here to there");
reader.Close();
//destination.Close();
}
catch (Exception e)
{
ex = e;
}
I actually wrote an ORM to make this kind of task easier.
var accessDS = new AccessDataSource(connectionString1);
var dt = accessDS.From("RCM_MF_New_Accounts_Samples").ToDataTable().Execute();
var sqlDS = new SqlServerDataSource(connectionString2);
sqlDS.InsertBulk("Load_CTR_Sample_Account_Opening2", dt).Execute();
This does not work for .NET Core.
Packages:
https://www.nuget.org/packages/Tortuga.Chain.Access/
https://www.nuget.org/packages/Tortuga.Chain.SqlServer
Read the data from Access into a DataTable:
string strConnect = #"Provider=Microsoft.ACE.OLEDB.12.0;data source=D:\Temp\MyDB.accdb";
DataTable dt = new DataTable();
using (OleDbConnection con = new OleDbConnection(strConnect))
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM MyTable", con);
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
Then use SqlBulkCopy to update SQL:
string strConnect = #"Data Source=GRIFFPC\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlBulkCopy bulk = new SqlBulkCopy(con))
{
bulk.DestinationTableName = "Test";
bulk.WriteToServer(dt);
}
}
Of course, there is a much easier way to go straight from Access to SQL Server, using VBA, SQL , or other methods.
https://support.office.com/en-us/article/import-or-link-to-data-in-an-sql-server-database-a5a3b4eb-57b9-45a0-b732-77bc6089b84e
https://www.sqlshack.com/six-different-methods-to-copy-tables-between-databases-in-sql-server/
Here's a basic example of bulk insert.
public void BulkInsert(DataTable employees)
{
if (employees == null)
throw new ArgumentNullException(nameof(employees), $"{nameof(employees)} is null.");
using (var con = OpenConnection())
using (var sbc = new SqlBulkCopy(con))
{
sbc.DestinationTableName = "HR.Employee";
foreach (DataColumn column in employees.Columns)
sbc.ColumnMappings.Add(column!.ColumnName, column.ColumnName);
sbc.WriteToServer(employees);
}
}
Note the foreach (DataColumn column in employees.Columns) loop. This is required so that it knows the column names are the same in the source and the target table. (If they're not the same, manually map them in the same fashion.)
Source: https://grauenwolf.github.io/DotNet-ORM-Cookbook/BulkInsert.htm#ado.net
Following option need to verify
1) Column Name should be the same.
2) verify the column length.
3) verify the data type.
Hi im trying to insert data into my DataBase. The program runs but it never save the values!!.
heres the code:
using System.Data.SqlClient;
namespace Database_1._0
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"DataSource=LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Luis\documents\visual studio 2015\Projects\Database_1._0\Database_1._0\DB.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
DateTime dateTime = DateTime.UtcNow.Date;
string user = "1614258779876465426";
string pass = "3Cp5CeXrfghdfght";
string frecuencyCode = "ANNUAL";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
}
private void logo_Click(object sender, EventArgs e)
{
MessageBox.Show("Database_1._0 \nWritten by: Luis", "About");
}
private void button1_Click(object sender, EventArgs e)
{
cn.Open();
using (SieteWS SieteWS = new SieteWS())
{
Respuesta respuesta = SieteWS.SearchSeries(user, pass, frecuencyCode);
foreach (internetSeriesInfo seriesInfo in respuesta.SeriesInfos)
{
cmd.CommandText = "INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency]) VALUES (#SerieID, #SerieName, #SerieFrecuency)";
cmd.Parameters.AddWithValue("#SerieID", seriesInfo.seriesId);
cmd.Parameters.AddWithValue("#SerieName", seriesInfo.spanishTitle);
cmd.Parameters.AddWithValue("#SerieFrecuency", seriesInfo.frequency);
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
}
}
and the Error says:
errorCS0103: The name 'CommandText' does not exist in the current context. And when I use a watch I found out this: cmd.CommandText =""; . Can somebody tell me what im doing wrong please.?
So first of all. move cn.Close(); outside of the loops. If it's not the cause for your problem now, it will cause a problem later.
If that doesn't fix your problem look further.
It's just a poke in the dark given the information I have, but try running following code sets (inside foreach loop) and see if any of them work:
set 1:
cmd = new SqlCommand("INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency])
VALUES ('"+seriesInfo.seriesId+"', '"+seriesInfo.spanishTitle+"'
, '"+seriesInfo.frequency+"')", cn);
cmd.ExecuteNonQuery();
set 2:
cmd = new SqlCommand("INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency])
VALUES (#SerieID, #SerieName, #SerieFrecuency)", cn);
cmd.Parameters.AddWithValue("#SerieID", seriesInfo.seriesId);
cmd.Parameters.AddWithValue("#SerieName", seriesInfo.spanishTitle);
cmd.Parameters.AddWithValue("#SerieFrecuency", seriesInfo.frequency);
Let me know how it works out
Try this...
Modify the line below to include the name of the database. So that it will read [Your database Name].[dbo].[Serie]
cmd.CommandText = "INSERT INTO [dbo].[Serie] ([SerieID], [SerieName], [SerieFrecuency]) VALUES (#SerieID, #SerieName, #SerieFrecuency)";
Your default database may not be the one that has your "Serie" table in it.
I'm new into c# programming and I'm trying for a while to debug this but so far I found no answer that could help me.
I'm trying to add a new record into a MSSQL database and I get the following error each time:
{"Input string was not in a correct format."}
My code is below:
private void btnAdd_Click(object sender, EventArgs e)
{
string cs = "Data Source=CODRINMA\\CODRINMA;Initial Catalog=TrafficManager;Integrated Security=True";
string insert = "INSERT INTO Companii (IDCompanie, Denumire, Adresa, Oras, CUI) VALUES (#IDCompanie, #Denumire, #Adresa, #Oras, #CUI)";
try
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand(insert, con);
cmd.Parameters.AddWithValue("#IDCompanie", txtID.Text);
cmd.Parameters.AddWithValue("#Denumire", txtDenumire.Text);
cmd.Parameters.AddWithValue("#Adresa", txtAdresa.Text);
cmd.Parameters.AddWithValue("#Oras", int.Parse(cmbOrase2.SelectedValue.ToString()));
cmd.Parameters.AddWithValue("#CUI", txtCUI.Text);
int val = cmd.ExecuteNonQuery();
MessageBox.Show(val + "Compania a fost adaugata cu succes!");
con.Close();
this.Dispose();
}
}
catch (Exception er) { MessageBox.Show(er.Message); }
}
The combobox Orase2 is binded with some values from a MSSQL database. Please, need some help! Thanks.
I have changed the combobox.ValueMember and it worked. I was converting to string when in fact I already had the int value.
I have question about my problem. Thru manustrip in form1 i have made new form2 when i click on a right option. This form is for deleting data in access database if you pick in combobox ID of row it deletes the whole row wher is ID 4 or somethig else... My combobox is connected on my database.
my code:
public partial class Form2 : Form
{
public string myConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Bojan\Desktop\Programiranje\School\Novo\Novo\Ure.accdb"; // to je provider za Access 2007 in več - če ga ni na lokalni mašini ga je treba namestiti!!!
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dataSet1.Ure' table. You can move, or remove it, as needed.
this.ureTableAdapter.Fill(this.dataSet1.Ure);
}
private void Brisanje_Click(object sender, EventArgs e)
{
OleDbConnection myConnection = null;
myConnection = new OleDbConnection(); // kreiranje konekcije
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
OleDbCommand cmd = myConnection.CreateCommand();
cmd.Connection = myConnection;
cmd.CommandText = "DELETE FROM Ure WHERE (ID) = '"+Izbor.SelectedValue+"'";
cmd.ExecuteNonQuery();
cmd.Prepare();
myConnection.Close();
}
}
Thanks for your help
As #musefan pointed out, you should really be using parameterised queries, the other issue seems to be the single quotes around ID which will result in a data type mismatch error. Finally, your connection and command objects implement IDisposable so I would recommend wrapping them in a using block.
The following code should work
using (var myConnection = new OleDbConnection(myConnectionString))
using (var myCommand = myConnection.CreateCommand())
{
var idParam = new OleDbParameter("#id", Izbor.SelectedValue);
myCommand.CommandText = "DELETE FROM Ure WHERE (ID) = #id";
myCommand.Parameters.Add(idParam);
myConnection.Open();
myCommand.ExecuteNonQuery();
}