Table.dbo object? - c#

I'm trying to add a record but I get an exception. Any ideas?
private void Form1_Load(object sender, EventArgs e)
{
string _connStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
string _query = "INSERT INTO Table1 VALUES ('MS','AH','BOSS')";
DataSet _ds = new DataSet();
try
{
using (SqlConnection _conn = new SqlConnection(_connStr))
{
SqlDataAdapter _da = new SqlDataAdapter(_query, _conn);
_conn.Open();
_da.Fill(_ds);
}
// insert null dataset or invalid return logic (too many tables, too few columns/rows, etc here.
if (_ds.Tables.Count == 1)
{ //There is a table, assign the name to it.
MessageBox.Show("1");
_ds.Tables[0].TableName = "Table1";
}
//Then work with your tblWorkers
MessageBox.Show(_ds.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Console.Write("An error occurred: {0}", ex.Message);
}
}
how can i add a record to the table?? data type is nchar

Try this:
string _connStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
string _query = "INSERT INTO Table1 VALUES ('MS','AH','BOSS')";
using (SqlConnection _conn = new SqlConnection(_connStr))
{
SqlCommand _com = _conn.CreateCommand();
_conn.Open();
_com.CommandText = _query;
_com.ExecuteNonQuery();
}
In general:
SqlDataAdapter (and DataSet.Fill method) are used for reading data in first turn (and update loaded data set in case you change it). Read MSDN on this subject
SqlCommand is used for executing sql queries

additionally your INSERT command will only work if you have 3 fields in your table. If you have more than three fields you need to explicitly declare which three fields you want to insert those values into.
INSERT INTO TableName (Field1, Field2, Field3) VALUES ('MS','AH','BOSS')

Related

Insert Data in Acces DB using C# and Parameters.AddWithValue

I try to insert some data in an Acces database using Parameters.AddWithValue
but the result is that there is an error in the insert clause
private const string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\andres\" +
#"Documents\synchro.accdb";
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection(conString);
OleDbCommand cmd;
public void setData(string temperature, string humidity,int month,int day,int year,string session)
{
//SQL STMT
const string sql = "INSERT INTO termohigrometer(temperature,humidity,month,day,year,session) VALUES(#TEMPERATURE,#HUMIDITY,#MONTH,#DAY,#YEAR,#SESSION)";
cmd = new OleDbCommand(sql, conn);
Console.Write("temperatura "+temperature);
cmd.Parameters.AddWithValue("#TEMPERATURE", temperature);
cmd.Parameters.AddWithValue("#HUMIDITY", humidity);
cmd.Parameters.AddWithValue("#MONTH", month);
cmd.Parameters.AddWithValue("#DAY", day);
cmd.Parameters.AddWithValue("#YEAR", year);
cmd.Parameters.AddWithValue("#SESSION", session);
Console.Write("query " +cmd.CommandText );
try
{
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show(#"Successfully Inserted");
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}
}
this is the result of the cmd.CommandText
INSERT INTO termohigrometer(temperature,humidity,month,day,year,session)
VALUES(#TEMPERATURE,#HUMIDITY,#MONTH,#DAY,#YEAR,#SESSION)
This is the exception message
These words month,day,year,session are reserved words for MS-Access. If you have fields with these names I strongly suggest you to change them to something different. Otherwise you need to put square brackets around them to avoid confusing the Jet Sql Engine.
const string sql = #"INSERT INTO termohigrometer
(temperature,humidity,[month],[day],[year],[session])
VALUES(#TEMPERATURE,#HUMIDITY,#MONTH,#DAY,#YEAR,#SESSION)";
Consider also to replace the AddWithValue method with the more precise Add method with a datatype for the parameter
cmd.Parameters.Add("#TEMPERATURE", OleDbType.VarWChar).Value = temperature;
....
Read this well known post about the dangers inside this 'convenient' method.
Can we stop using AddWithValue already?

Column 'Value' does not belong to table

I have stored some number data under column name Value in the tblV table of my database. I want to put the data from that column Value into textbox1.
But whenever I click the button it shows Column 'Value' does not belong to table error even though there is column Value in the table. What is causing this problem?
The first one is class and second one is the code on button click event.
public DataTable GetMaxno(decimal Licenseno)
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=sudipDB;");
string sql = "select Max(Value) from tblv where Licenseno=#licenseno";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Licenseno",Licenseno );
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable DT = new DataTable();
da.Fill(DT);
return DT;
}
tryv tv = new tryv();
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = tv.GetMaxno(Convert.ToDecimal(textBox2.Text));
if (dt.Rows.Count > 0)
{
textBox1.Text= dt.Rows[0]["Value"].ToString();
}
}
Reason might be that your query does not return any aliases as Value. You can solve this with select Max(Value) as Value but instead of that, use ExecuteScalar instead which is exactly what you want. It returns first column of the first row.
A few things more;
Use using statement to dispose your connection and command.
Do not use AddWithValue. It may generate unexpected and surprising result sometimes. Use Add method overloads to specify your parameter type and it's size.
public int GetMaxno(decimal Licenseno)
{
using(var con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB; Integrated Security=True; Initial Catalog=sudipDB;")
using(var cmd = con.CreateCommand())
{
cmd.CommandText = "select Max(Value) from tblv where Licenseno = #licenseno";
cmd.Parameters.Add("#licenseno", SqlDbType.Decimal).Value = Licenseno;
con.Open();
return (int)cmd.ExecuteScalar();
}
}
Then you can do;
textBox1.Text = tv.GetMaxno(Convert.ToDecimal(textBox2.Text)).ToString();
try
string sql = "select Max(Value) as Value from tblv where Licenseno=#licenseno";

I have to check if data exists or not in a database in Asp.Net

I have two methods, one to insert, update and delete and a second is checking whether data already exists in my database or not. The main purpose of all code is that I don't want to insert duplicate data into the database.
public class DAL : System.Web.UI.Page
{
SqlConnection connection;
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
public int numofrows;
//Connection Method
public void Connection()
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
connection.Open();
}
//This Method will Insert,Update and Delete in Database
public void InsertUpdateDelete(string query)
{
////connection = new SqlConnection("Data Source=IM-82B70624D72D;Initial Catalog=AppointmentScheduler;User ID=sa;Password=za3452432760za");
//connection = new SqlConnection(connectionString);
//connection.Open();
this.Connection();
cmd = new SqlCommand(query, connection);
numofrows = cmd.ExecuteNonQuery();
connection.Close();
}
//This Method will read data From Database
public DataTable ReadData(string Query)
{
this.Connection();
da = new SqlDataAdapter(Query, connection);
dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Redirect("Data already Exist");
}
return dt;
}
}
I have to use both above code in index.aspx. How can I use both above code in index.aspx?
I tried to use but that is not working.
index.aspx code:
protected void btnSaveDays_Click(object sender, EventArgs e)
{
this.query = "SELECT DaysName FROM Dayss WHERE Day_Id='" + DropDownListDays.SelectedValue + "'";
dal.ReadData(this.query);
this.query = "INSERT INTO Dayss VALUES ('" + DropDownListDays.SelectedItem.Text + "')";
dal.InsertUpdateDelete(this.query);
Response.Write("Day Inserted Successfully");
}
But this code is not working and generating error
Conversion failed
not Day_Id is int, and Dayss have two columns. One is id and second is
name
Then there is no point to use single quotes with int typed column value. Single quotes is for character column values.
this.query = "SELECT DaysName FROM Dayss WHERE Day_Id = " + DropDownListDays.SelectedValue ;
And if you want to insert just one column, you need specify your column name in your Dayss table like;
this.query = "INSERT INTO Dayss (YourColumnName) VALUES ('" + DropDownListDays.SelectedItem.Text + "')";
Take a look INSERT (Transact-SQL)

insert in sql using c#

this code is successfully inserting a new value in a SQL db, but only when I insert constant values.
I need help where it says **(?)** in the code below, where I want to insert new values without specifying constants in the code.
What I mean is, I want to be able to type any random value in output window and it gets inserted into the SQL db.
private void InsertInfo()
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
connetionString = #"Data Source=HP\SQLEXPRESS;database=MK;Integrated Security=true";
connection = new SqlConnection(connetionString);
string sql = "insert into record (name,marks) **values( ?))";**
try
{
connection.Open();
adapter.InsertCommand = new SqlCommand(sql, connection);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show ("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void insert_Click(object sender, EventArgs e)
{
InsertInfo();
}
There is no need to use an adapter here; that is not helping you. Just:
var name = ...
var marks = ...
using(var conn = new SqlConnection(connectionString))
using(var cmd = conn.CreateCommand()) {
cmd.CommandText = "insert into record (name, marks) values (#name, #marks)";
cmd.Parameters.AddWithValue("name", name);
cmd.Parameters.AddWithValue("marks", marks);
conn.Open();
cmd.ExecuteNonQuery();
}
or with a tool like "dapper":
var name = ...
var marks = ...
using(var conn = new SqlConnection(connectionString)) {
conn.Open();
conn.Execute("insert into record (name, marks) values (#name, #marks)",
new {name, marks});
}
Those '?' are termed as parameters. From what I understand, you are wanting to use a parametrized query for your insert which is a good approach as they save you from chance of a SQL injection. The '?' sing in your query is used when you are using an
OLEDBConnection & Command object.
Normally, you would use '#' symbol to specify a parameter in your query. There is no need for an adapter. You just
//Bind parameters
// Open your Connection
// Execute your query
// Close connection
// return result
Parametrized queries 4 Guys from Rolla
MSDN: How to Protect from SQL injection in ASP.NET

Retrieve number of columns in SQL Table - C#

I'm very new to C#. I'm trying to retrieve the number of columns using:
SELECT count(*) FROM sys.columns
Could you please explain how to use the command and put it into a variable.
To connect to the database you can use the SqlConnection class and then to retrieve the Row Count you can use the Execute Scalar function. An example from MSDN:
cmd.CommandText = "SELECT count(*) FROM sys.columns;";
Int32 count = (Int32) cmd.ExecuteScalar();
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection
You will need to use ExecuteScalar as the others have said. Also, you will need to filter your SELECT on the object_id column to get the columns in a particular table.
SELECT count(*) FROM sys.columns WHERE object_id = OBJECT_ID(N'table_name')
Alternatively, you could do worse than familiarise yourself with the ANSI-standard INFORMATION_SCHEMA views to find the same information in a future-proof, cross-RDBMS way.
You have to use a command and retrieve back the scalar variable :
SqlCommand cmd = new SqlCommand(sql, conn);
Int32 count = (Int32)cmd.ExecuteScalar();
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
string queryString =
"SELECT Count(*) from sys.columns";
// Specify the parameter value.
int paramValue = 5;
// Create and open the connection in a using block. This
// ensures that all resources will be closed and disposed
// when the code exits.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(queryString, connection);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}",
reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
use Executescalar() for getting a single element.
using (SqlConnection con = new SqlConnection(ConnectionString)) //for connecting to database
{
con.Open();
try
{
using (SqlCommand getchild = new SqlCommand("select count(*) from table1 ", con)) //SQL queries
{
Int32 count = (Int32)getchild.ExecuteScalar();
}
}
}
Use ExecuteScalar
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
Int32 colnumber = 0;
string sql = "SELECT count(*) FROM sys.columns";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
colnumber = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
You'll want to use the ADO .NET functions in the System.Data.SqlClient namespace. ExecuteScalar is an easy-to-use method when you only want to get a single result. For multiple results, you can use a SqlDataReader.
using System.Data.SqlClient;
string resultVar = String.Empty;
string ServerName="localhost";
string DatabaseName="foo";
SqlConnection conn=new SqlConnection(String.Format("Data Source={0};Initial Catalog={1};Integrated Security=SSPI",ServerName,DatabaseName));
SqlCommand cmd=new SqlCommand(Query,conn);
try
{
conn.Open();
}
catch (SqlException se)
{
throw new InvalidOperationException(String.Format(
"Connection error: {0} Num:{1} State:{2}",
se.Message,se.Number, se.State));
}
resultVar = (string)cmd.ExecuteScalar().ToString();
conn.Close();

Categories

Resources