Local SQL Server connection fail - sql-server

I'm trying to connect to a local SQL Server database file and do not know if connection string is right:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\ma\Documents\mydb.mdf;Integrated Security=True;");
SqlDataAdapter sda = new SqlDataAdapter("SELECT plataform FROM plataforms", con);
DataSet myDataSet = new DataSet();
sda.Fill(myDataSet);
I have such code wrapped in a try catch and always throws this exception:
Reference to object not established as an instance of an object
What's wrong?
EDIT:
Sorry, I have been commenting code to see what line arises such error and it's the following:
DataRowCollection drc = myDataSet.Tables["plataforms"].Rows;
Sorry, I made a wrong question.

I think You must open connection before Fill
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\ma\Documents\mydb.mdf;Integrated Security=True;");
SqlDataAdapter sda = new SqlDataAdapter("SELECT plataform FROM plataforms", con);
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = sda;
DataSet myDataSet = new DataSet();
try {
con.Open();
sda.Fill(myDataSet);
} catch (Exception ex) {
throw (ex);
} finally {
con.Close();
}
you can try this code.

Related

No value given for one or more required parameters.What is error in query

if (conn.State == ConnectionState.Closed) { conn.Open(); }
string sql = "SELECT debit.tblgltransactions AS Debit,credit.tblgltransactions AS Credit,glaccounttype.tblglaccounttypes from tblgltransactions,tblglaccounttypes where glaccounttype.tblglaccounttypes='" + cmbGeneralLedgerAccounts + "'and transactiondate.tblgltransactions='"+dtpFromDate+"'AND '"+dtpToDate+"'";
OleDbCommand cmd = new OleDbCommand(sql, conn);
OleDbDataAdapter oda = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
oda.Fill(dt);
dgvGeneralLedger.DataSource = dt.DefaultView;
if (conn.State == ConnectionState.Open) { conn.Close(); }
Maybe you missed a space in front of those "AND" statements?
And as far as I can see you are referring to transactiondate table without declaring it in from or a join statement.
EDIT:
You dont referrence both of the tables in the where condition. Dont know how that should work.

Conversion failed when converting from a character string to uniqueidentifier - Doesn't Rollback the transaction

The actual issue is not this - "Conversion failed when converting from a character string to uniqueidentifier" but the issue is that, the transaction doesn't get rolled back after you hit the issue.
My code here,
var connectionstring = "Server= ****; Database= ****; Integrated Security=True;";
var errorInformation = new List<string>();
using (SqlConnection objConn = new SqlConnection(connectionstring))
{
objConn.Open();
var objTrans = objConn.BeginTransaction(); // Begins here
var sql = $"insert into tblProject values('7', 'TestProject')";
SqlCommand insertCommand = new SqlCommand(sql, objConn, objTrans);
try
{
insertCommand.ExecuteNonQuery();
// ProjectID is a unique Identifier in database
SqlCommand cmd = new SqlCommand("SELECT * FROM SOMEOTHERTABLE WHERE PROJECTID=''", objConn, objTrans);
cmd.CommandType = CommandType.Text;
var dataTable = new DataTable("SomeTableName");
using (var adapter = new SqlDataAdapter(cmd))
{
var dt = adapter.Fill(dataTable); // Exception happens here
}
objTrans.Commit(); // Commit here
}
catch (Exception ex)
{
errorInformation.Add(ex.Message);
}
var sql1 = $"insert into tblProject values('8', 'TestProject')";
SqlCommand objCmd2 = new SqlCommand(sql1, objConn, objTrans);
objCmd2.ExecuteNonQuery();
if (errorInformation.Any())
{
objTrans.Rollback(); // Rollback here
}
}
The query that gets executed after the exception, using the same connection object will not rollback. This is a bug that Microsoft needs to look into. Otherwise their rollback feature is not reliable.
I would expect either my second insert command to fail or my rollback to be successful.

SqlDataReader Close and SqlConnection

What happens with the connection in this case? I don't know if reader.Close() close the open sqlconnection.
private static void ReadOrderData(string connectionString)
{
string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
}
// Call Close when done reading.
reader.Close();
}
}
reader.Close() won't close the SqlConnection, but since you have a using statement, once you exit the using block the connection will get closed anyway.
Closing the reader will not alter the state of the connection. If you did want to do this you can pass CommandBehavior.CloseConnection to the ExecuteReader method of the SqlCommand instance.
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
It is recommended you put a using block around all your disposable types like your SqlDataReader instance.
using(SqlDataReader reader = command.ExecuteReader()) {
// rest of code
}
See also CommandBehavior for more options.
Check Connection State
if(connection.State == ConnectionState.Open)
{
connection.Close();
}
connection.Open();
And since you are doing
using (SqlConnection connection =
new SqlConnection(connectionString))
{
this will make sure connection is disposed as it inherits from IDisposable despite Exception. And object are disposed once they exit their corresponding scope.
And better use
using(SqlCommand command = new SqlCommand(queryString, connection))
and
using(SqlDataReader reader = command.ExecuteReader())
for the same reason mentioned above.

Displaying data from a dataset vb.net

I am having issues returning data from a MS SQL database.
The code is returning 'System.data.datarowview' instead of the results of my query. The code for the sub is:
Public Sub newquery(query As String)
Dim SQLConn As SqlConnection = New SqlConnection
Dim SqlCommand As New SqlCommand
SQLConn.ConnectionString = "Data Source=.\testing;Initial Catalog=eurostyle;Integrated Security=SSPI;"
SqlCommand = New SqlCommand(query, SQLConn)
Try
SQLConn.Open()
sqlDA = New SqlDataAdapter(SqlCommand)
sqlDataset = New DataSet
sqlDA.Fill(sqlDataset)
SQLConn.Close()
listbox1.DataContext = sqlDataset
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I am new to WPF and I'm sure that is only something trivial.
Any help is greatly appreciated!
DataGrid view would be more appropriate to display results from database.
Try this:
Public Sub newquery(query As String)
Dim SQLConn As SqlConnection = New SqlConnection
Dim SqlComm As New SqlCommand
Dim dbDataSet As New DataTable
Dim bSource As New BindingSource
Dim sqlDA As New SqlDataAdapter
SQLConn.ConnectionString = "Data Source=.\testing;Initial Catalog=eurostyle;Integrated Security=SSPI;"
Try
SQLConn.Open()
SqlComm = SQLConn.CreateCommand
SqlComm.CommandText = query
SqlComm = New SqlCommand(zapytanie, myConn)
sqlDA.SelectCommand = SqlComm
sqlDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
DataGridView.DataSource = bSource
sqlDA.Update(dbDataSet)
SQLConn.Close()
Catch ex As SqlException
MessageBox.Show("Query Error: " & ex.Message)
End Try

Change DataBase using DataGrid

I want to output data from DataBase to DataGrid, using ADO.NET.
Can you tell me how to do that?
When I'm writing something in dataGrid it's changing in database. I use WPF, .NET 4.0.
Code:
class ThemeEditor
{
private SqlDataAdapter da;
private DataSet ds;
private SqlConnection cn;
public ThemeEditor(DataGrid dg)
{
SqlCommand cmd;
string source = "server=(local); integrated security=SSPI; database=tests";
string reqest = "SELECT Theme,Stuff FROM Themes";
cn = new SqlConnection(source);
da = new SqlDataAdapter();
ds = new DataSet();
cmd = new SqlCommand(reqest, cn);
da.SelectCommand = cmd;
da.Fill(ds, "Theme");
dg.ItemsSource = ds.Tables["Theme"].DefaultView;
}
}
maybe it'll be helpfull!
http://support.microsoft.com/kb/307587
or this... http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/3adacd01-f08f-4059-bbce-bff736a5188e

Resources