Trouble inserting data into a SQL Server CE databse - c#-4.0

I am new to C# and was experimenting a bit trying to insert stuff into a SQL Server CE database. I don't understand why this code is not working. I am getting a
System.Data.SqlServerCE.SqlCeException
error pointing to the com1.ExecuteNonQuery(); line when the program is run.
I am attaching my code that i am using to insert into the table.
//Connecting to SQL Server
SqlCeConnection conn1 = new SqlCeConnection();
conn1.ConnectionString = connection; //connection is a string variable which has the connection details
conn1.Open();
SqlCeCommand com1 = new SqlCeCommand();
com1.Connection = conn1;
com1.CommandType = CommandType.Text;
com1.CommandText = "INSERT into data(pname, budget, dcommision, advance, phone, cdetails, mail) values(#pname , #budget, #dcommision, #advance, #phone, #cdetails, #mail)";
com1.Parameters.AddWithValue("#pname", textBox8.Text.Trim());
com1.Parameters.AddWithValue("#budget", budget);
com1.Parameters.AddWithValue("#dcommision", textBox7.Text.Trim());
com1.Parameters.AddWithValue("#advance", advance);
com1.Parameters.AddWithValue("#phone", phone);
com1.Parameters.AddWithValue("#cdetails", richTextBox1.Text.Trim());
com1.Parameters.AddWithValue("#mail", textBox3.Text.Trim());
com1.ExecuteNonQuery(); //Executing the SQL query
com1.Dispose(); //Closing SQL Server connection
conn1.Close();
Is something wrong with my query? I am really a newbie so some help would be really appreciated. Thanks

Your table data have also column cname which you don't include in INSERT list, and column i marked as NOT NULL. Include the column too into INSERT list or provide DEFAULT value for this column in DB.

Related

Getting "Please rebuild this data combination" on a computer but not on another one

This is my first try at using the Power Query... I've build a "dynamic" query in which I can change the retrieved fields as well as the filtering fields and values to be used by the query.
It's working perfectly on my computer but as soon as I try to execute it on another computer, I get the "Please rebuild this data combination" error. I saw some post saying I'll have to kind of split my query but I have not been able to figure it out.
Here is what my 2 tables look like:
Condition and fields selection
and here is my Query with the error:
Query
This might not be very elegant, but it allow me, thru a VBA script, to generate the list of fields to be retrieved and to generate the condition to be used by the SQL.
Any idea why it's not working on the other computers or how to improved the solution I'm using?
Thank you!
Notes:
Hi, all my Privacy Level are already set to 'None'.
I've tried to parametrize my code but I can't figure how. The Where condition is dynamic: it could be Where Number = "1234" but in other condition, the where might be like: 'Where Assignee = "xyz"'.
Here is a simplified example of my code:
let
Source = Sql.Database("xxxx", "yyyy", [Query=
"Select network, testid
from CM3T1M1 "
& paramConditions[Conditions]{0} &
" "])
in
Source
rebuild query, Formula.Firewall
That's a feature to prevent prevent accidentally leaking data. You can change the privacy level to ignore it
See also: docs.microsoft/dataprivacyfirewall
Is the dynamic query inserting those cells into the SQL query ? Report Parameters are nice for letting the user change variables without having to re-edit the query.
Parameterized native SQL queries
from: https://blog.crossjoin.co.uk/2016/12/11/passing-parameters-to-sql-queries-with-value-nativequery-in-power-query-and-power-bi/
let
Source = Sql.Database("localhost", "Adventure Works DW"),
Test = Value.NativeQuery(
Source,
"SELECT * FROM DimDate
WHERE EnglishMonthName=#MonthName AND
EnglishDayNameOfWeek=#DayName",
[
MonthName = "March",
DayName = "Tuesday"
]
)
in
Test
Dynamic Power Query version of SQL Query
To dynamically generate this SQL Query
select NUMBER, REQUESTED_BY from SourceTable
where NUMBER = 404115
Table.SelectRows is your Where.
SelectColumns is your select
let
Source = ...,
filterByNum = 404115,
columnNames = {"NUMBER", "REQUESTED_BY"},
removedColumns = Table.SelectColumns(
Source, columnNames, MissingField.Error
),
// I used 'MissingField.Error' so you know right away
// if there's a typo or bug
// assuming you are comparing Source[NUMBER]
filteredTable = Table.SelectRows(
Source, each [NUMBER] = filterByNum
)
in
filteredTable

Pypyodbc query returning incorrect data

Hi there so bit of an odd one, the sql query im running is
SELECT [idPerson] FROM tblPersons WHERE [Email] LIKE 'Joe.Pike%'
If i run this in the server i get my correct personID, however when i run it in my code i get a random personID that doesn't exist, now what is even weirder is that my second bit of code queries based on the personID and that returns a value
UserName = row[1]+'.'+row[2]
Password = 'XXXXXXXX'
Email = UserName + '#XXXXXXX.org.uk'
emaillike = [str(row[1]+'.'+row[2]).replace("'", '')+"%"]
sql = ("""SELECT [idPerson] FROM tblPersons WHERE [Email] LIKE {}""").format(str(emaillike).replace("[","").replace("]",""))
PersonId = cursor.execute(sql).fetchone()
PersonPin = \
str(cursor.execute('SELECT [Pin] FROM tblPersonPins WHERE [PersonId] = ?'
, [PersonId[0]]).fetchone()).replace("'","").replace("(","").replace(")","").replace(",","")
print(sql)
print(emaillike)
print(str(PersonId))
print(PersonPin)
I have even tried to fetchall rows with the Email LIKE query but that still only returned one ID and that is the non existent 105524 value
The sql server is MSSQL server 2017 and im running Python 3.7.2
It also appears to be an issue with pyodbc as well as pypyodbc
My print statements return :
SELECT [idPerson] FROM tblPersons WHERE [Email] LIKE 'Joe.Pike%'
['Joe.Pike%']
(105524,)
7271
But the numbers should both be different and once again to confirm when I run the printed sql statement in sql server developer it returns the correct data.
thanks in Advance
P.S this is unfinished code so please ignore the terrible formatting (I also know i should not be using positional parameters for sql queries but I can't see any other way to achieve the end result)
OMG please shoot me!
Incorrect database, Man I wish I could Delete questions

Connect Excel to PostgreSQL via ODBC

I am trying to connect to a PostgreSQL database table from Excel via the PostgreSQL ODBC 32-bit driver.
In Excel, I go to Data>Get Data> From Other Sources> From ODBC. I navigate to the ODBC data source I set up, enter the credentials, and it clearly connects as the available tables appear. The preview fails and the query fails when I hit "Load" giving the error:
DataSource.Error: ODBC: ERROR [HY000] Error while executing the query
Details:
DataSourceKind=Odbc
DataSourcePath=dsn=PostgreSQL
OdbcErrors=Table
When I test the connection in ODBC admin it is successful. I have tried both the ANSI and Unicode drivers. TIBCO Spotfire connects to the ODBC datasource and pulls the data in just fine.
Any help you can provide would be greatly appreciated.
This appears to be a bug with the latest psqlODBC driver, which is psqlodbc_09_06_0500 at the time I'm writing this. I have access to my PostgreSQL server logs. Here's the error message and the offending query:
ERROR: syntax error at or near "ta" at character 553
STATEMENT: select ta.attname, ia.attnum, ic.relname, n.nspname, tc.relname from pg_catalog.pg_attribute ta, pg_catalog.pg_attribute ia, pg_catalog.pg_class tc, pg_catalog.pg_index i, pg_catalog.pg_namespace n, pg_catalog.pg_class ic where tc.relname = 'rates' AND n.nspname = 'public' AND tc.oid = i.indrelid AND n.oid = tc.relnamespace AND i.indisprimary = 't' AND ia.attrelid = i.indexrelid AND ta.attrelid = i.indrelid AND ta.attnum = i.indkey[ia.attnum-1] AND (NOT ta.attisdropped) AND (NOT ia.attisdropped) AND ic.oid = i.indexrelid order by ia.attnumselect ta.attname, ia.attnum, ic.relname, n.nspname, NULL from pg_catalog.pg_attribute ta, pg_catalog.pg_attribute ia, pg_catalog.pg_class ic, pg_catalog.pg_index i, pg_catalog.pg_namespace n where ic.relname = 'rates_pkey' AND n.nspname = 'public' ANDic.oid = i.indexrelid AND n.oid = ic.relnamespace AND ia.attrelid = i.indexrelid AND ta.attrelid = i.indrelid AND ta.attnum = i.indkey[ia.attnum-1] AND (NOT ta.attisdropped) AND (NOT ia.attisdropped) order by ia.attnum
Here's the context around character 553: order by ia.attnumselect ta.attname, ia.attnum. Note that it's missing a comma between two field names.
I was able to get it working with psqlodbc_09_06_0200, which is about a year old. Since it sounds like you use 32-bit Office, you can download psqlodbc_09_06_0200-x86.zip from https://www.postgresql.org/ftp/odbc/versions/msi/. (Use x64 if you have 64-bit Office installed.)
You might be able to experiment with driver versions between psqlodbc_09_06_0200-x86.zip and psqlodbc_09_06_0500-x86.zip as the bug was presumably introduced somewhere between those two versions.
You can skip this error by removing the navigate step and querying the information you need throw an SQL statement.
For example if you want to retry some information from LineItemExport the default query is something like this:
let
Source = Odbc.DataSource("dsn=name", [HierarchicalNavigation=true]),
quickbase_Database = Source{[Name="quickbase",Kind="Database"]}[Data],
public_Schema = quickbase_Database{[Name="public",Kind="Schema"]}[Data],
LineItemExport = public_Schema{[Name="LineItemExport",Kind="View"]}[Data]
in
LineItemExport
You have to change the source step in the query editor or change the code to something like this:
let
Source = Odbc.Query("dsn=name", "select * from public.LineItemExport")
in
Source
This is the way you can came over the error, otherwise you should try to change your drivers version.

node.js - full mysql output for the query - where is it?

I can connect to mysql ok.
i want to get the full raw data
of the query.
in python i think all data is stored in
rows[0]
i am not certain how it is in node.js
i want to print the full mysql output
i want to assign it to the variable "bb"
connection.connect();
var queryString = 'SELECT * FROM 1_accounts';
connection.query(queryString, function(err,rows,fields){
bb = rows[0].toString();
});
connection.end();
If you want to see a text representation of rows use JSON.stringify(rows) instead of rows.toString()

ADO on Access Lookup field, getting wrong field returned

I'm in Excel 2010 VBA, using ADO 2.8 to query an Access 2010 database. I don't own the database and don't have any authority to make any changes to it. I've been working with Excel VBA for many years but my Access knowledge is sketchy.
Using the same SQL as one of the queries in the database (copied from the Access query and pasted into Excel VBA), I get different results in some fields than that query in the database gets.
For the affected fields, I see that in Access those fields are defined as lookups. Here's an example lookup from one of the affected fields' Row Source property:
SELECT [Signers].[SignerID], [Signers].[SignerName] FROM Signers ORDER BY [SignerID], [SignerName];
In the Access database, where the SQL statement refers to that field, the query returns SignerName.
But in my ADO code, where the very same SQL statement refers to that field, the query returns SignerID, not SignerName.
Is there something I can do from my ADO code to get SignerName instead of SignerID, from the same SQL statement? Or do I need to modify the SQL statement?
Thanks,
Greg
Update:
On the Access side, I think I see now why only SignerName appears. On the field's Lookup tab, the Column Widths property is:
0";1.2605"
So I guess SignerID is there in the Access query result but with a column width of 0.
Unfortunately that doesn't help me on the ADO side. Any suggestions on getting SignerName instead of SignerID in the ADO query result?
Update2:
Here's a sample SQL statement that returns different fields depending on either it's in Access or in ADO:
SELECT MasterAccount.[SignerKey1]
FROM MasterAccount ;
Per Preet's request, here's the ADO code in Excel VBA:
strDatabasePath = rgDatabasePathCell.Value 'rgDatabasePathCell is a worksheet cell object.
strPWD = DATABASE_PASSWORD
Set cnn = New ADODB.Connection
cnn.Provider = "Microsoft.ACE.OLEDB.12.0"
cnn.ConnectionString = "Data Source='" & strDatabasePath & "';Jet OLEDB:Database Password='" & strPWD & "';"
cnn.Open
Set cmd = New ADODB.Command
cmd.ActiveConnection = cnn
cmd.CommandType = adCmdText
cmd.CommandText = strSQL
Set rst = New ADODB.Recordset
rst.Open cmd.Execute
shMA.Cells(2, 1).CopyFromRecordset rst 'shMA is a worksheet object.
Update 3:
It occurred to me that from what I've said so far, it might seem like I could just change this:
SELECT MasterAccount.[SignerKey1]
FROM MasterAccount ;
to this:
SELECT [Signers].[SignerName]
FROM MasterAccount ;
But there are 13 affected lookup fields, all with exactly the same "Row Source" property text as shown above, and all return different SignerName items for each row. I don't know why they are all returning different items per row; I have not been able to find any difference in the way they are defined. I've been tasked with getting the same result in Excel as that Access query gets.
Update 4:
VBlades -- Thanks, I found the form that has a tab with dropdowns for each of the 13 SignerKey-n fields. If I right-click that form and choose Form Properties, the RecordSource property is:
SELECT MasterAccount.*, Bank.BankRating FROM Bank INNER JOIN MasterAccount ON Bank.BankID = MasterAccount.Bank;
However I don't understand how that would be selecting a different SignerName item for each of the 13 SignerKey-n fields, or what to do with this information to get the same results in ADO as in the Access query. Any suggestions?
Update 5:
I may be close to a workaround. If I do this, I get the SignerName field for SignerKey1:
SELECT Signers.SignerName
FROM Signers RIGHT JOIN MasterAccount ON Signers.SignerID = MasterAccount.SignerKey1.Value;
And if I do this, I get different SignerName items for each field on each row:
SELECT Signers.SignerName, Signers_1.SignerName, Signers_2.SignerName
FROM Signers AS Signers_2 INNER JOIN (Signers AS Signers_1 INNER JOIN (Signers RIGHT JOIN MasterAccount ON Signers.SignerID = MasterAccount.SignerKey1.Value) ON Signers_1.SignerID = MasterAccount.SignerKey2.Value) ON Signers_2.SignerID = MasterAccount.SignerKey3;
That works both in an Access query and in ADO. Next step, I'll try to add these joins to the main SQL statement.
Update 6:
Well, when I try to add even one of those 13 joins to the main SQL statement, it works fine in an Access query, but in ADO I get the error:
Row handles must all be released before new ones can be obtained.
So I'm stuck. Any suggestions?
I've raised the issue with the database owner, but they don't know why the affected fields' Row Source property includes SignerID, so I'm not sure if that's going to help.
You can do the following (simplest way)
Exclude [Signers].[SignerID] from the Query
SELECT [Signers].[SignerName] FROM Signers ORDER BY [SignerID], [SignerName];
Or, create Composite field containing both [SignerID], [SignerName] and extract any part using VBA that you are familiar with:
SELECT ([SignerID] & "_" & [SignerName]) As Composite FROM Signers ORDER BY [SignerID], [SignerName]
Regards,
Okay, I worked around the problem by getting a separate recordset of the SignerID and SignerName fields from the Signers table.
Then I looped through all the rows of each affected field, looked up SignerID in the 2nd table, and swapped in SignerName for SignerID in the original table.
I tried to do that in ADO, but got the error "An UPDATE or DELETE query cannot contain a multi-valued field". So instead I made the swaps after copying the recordset to the Excel worksheet.
I would have liked to know how to handle it all in ADO, but this works. All is well now.

Resources